【问题标题】:Update boolean attributes to true or false将布尔属性更新为 true 或 false
【发布时间】:2017-08-22 18:16:37
【问题描述】:

我正在使用 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 列。关于我可能在这里做错了什么有什么想法吗?

【问题讨论】:

  • 您分配的cookies[:email] 将始终是present?。这是你想要的吗?
  • 感谢@sawa 的回复。是的,我需要cookies[:email] 始终存在。否则应用在登录或注册时不会更新is_active
  • if cookies["email"].present?的条件是什么?
  • current_client方法的目的是找到正在尝试登录或注册的current_store,并更新stores表下的is active列。

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


【解决方案1】:

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,而不是两者!

【讨论】:

  • 没有问题,很高兴它有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多