2017-08-02 87 views
0

我正在使用我的應用程序的設計寶石。我應該使用哪種回調以便在登錄過程中從我的用戶模型傳遞方法?登錄過程中的回調,以便將布爾值更改爲true或false

Warden::Manager.after_set_user ? before_validation? before_save? before_create?

方法細節: 我有一個布爾列:在用戶表IS_ACTIVE。 用戶每次嘗試登錄時,braintree代碼都會通過braintree api查找用戶是否擁有活動訂閱或未訂閱訂閱。如果用戶有活動或未訂閱,我正在嘗試將is_active列更新爲true或false。

我使用這個現在,但它不工作:

Warden::Manager.after_set_user :scope => :user do |user, auth, opts| 

    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 
    obj = User.find_by_id(params[:id]) 
    obj.is_active = true 
    obj.save! 

else 
    obj = User.find_by_id(params[:id]) 
    obj.is_active = false 
    obj.save! 
end 
end 

def active_for_authentication? 
    super && is_active? 
end 

def inactive_message 
    "User not active, please subscribe!" 
end 

回答

0

由於Braintree::Subscription::Status::Active僅僅是constant pointing to a string"Active",它總是 「truthy」。這意味着if Braintree::Subscription::Status::Active將永遠是真實的。

你可能想這樣做,而不是:

user.update(is_active: sub.status == Braintree::Subscription::Status::Active) 

沒有必要的條件或基於塊的條件明確設置truefalse,並且你已經有了一個User實例傳遞給塊,你不需要從數據庫加載一個。

+0

感謝您的回覆@coreyward!另外我的另一個問題是,我應該使用另一個回調,而不是'Warden :: Manager.after_set_user'? – Theopap

相關問題