将布尔属性更新为true或false

时间:2017-08-22 18:16:38

标签: ruby-on-rails ruby ruby-on-rails-4

我使用devise gem进行身份验证,登录或注册后,会创建一个Cookie:

cookies[:email] = {
  :value => params[:store][:email],
  :domain => :all,
  :expires => 1.hour.from_now
}

Cookie的目的是找到current_client

def current_client
  if cookies["email"].present?
   Store.find_by_email(params[:email])
  end
end

然后查看商店是否有有效的braintree订阅, 并将stores表下的is_active布尔值更改为truefalse

after_action :active_subscription
def active_subscription
  if current_client.present?
    customer_id = current_client.braintree_customer_id
    customer = Braintree::Customer.find(customer_id )
    customer_card = customer.payment_methods[0].token
    payment_method = Braintree::PaymentMethod.find(customer_card)
    sub = payment_method.subscriptions[0]
    sub.status

  if Braintree::Subscription::Status::Active
     current_client.update_attributes(is_active: true)
  end
end

但上面的active_subscription方法不会更新is_active列。关于我可能会在这里犯错的任何想法?

1 个答案:

答案 0 :(得分:2)

active_subscription方法中存在一些问题。

“如果”测试

if检查应将用户的状态与常量进行比较:

# always passes because it's only looking at the constant!
if Braintree::Subscription::Status::Active

# instead, compare the client's status to the constant
if sub.status == Braintree::Subscription::Status::Active

保存失败

由于验证错误,update_attributes调用可能失败。如果保存失败,则返回false,您可能没有注意到。您可以使用update_attributes!

来引发错误
current_client.update_attributes!(is_active: true)

如果出现此问题,您可以使用#update_attribute

绕过验证检查

其他问题

  1. 用户的订阅可能处于多种状态 - 您可能希望处理sub.status的其他值,并将is_active设置为false,如果它们未处于活动状态。
  2. current_client方法检查是否存在“电子邮件”Cookie,然后使用来自params[:email]的电子邮件,而不是cookies["email"]。它应该使用cookiesparams,而不是两者!
相关问题