2014-09-23 16 views
1

我有一個設置,我有Devise被用作Rails應用程序的主要身份驗證處理程序,有一次,它似乎拉出一個ActiveRecord關係而不是記錄,就像你可能以Type.where(name: "bob")爲例。紅寶石,如果條件奇怪似乎運行一些代碼時,條件爲假

爲了解決這個問題(我沒有花太多時間與Devise,我沒有太多的空閒時間花費探索)我只是想確保我的登錄檢查和糾正這一點,所以我寫了這樣一段:

def authenticate_user_with_assignment! 
    authenticate_user! 
    logger.debug("User is #{current_user.inspect}") 
    if (current_user.is_a?(ActiveRecord::Relation)) 
     logger.debug ("It is a relation!") 
     current_user = current_user.first 
    else 
     logger.debug ("Not a relation.") 
    end 
    logger.debug("User is #{current_user.inspect}") 
    # do some other stuff 
end 

我得到的輸出是這樣的:

User is #<User id: 1, email: "[email protected]" ... etc > 
Not a relation. 
User is nil 

如果我註釋掉current_user = current_user.first線,我得到這個:

User is #<User id: 1, email: "[email protected]" ... etc > 
Not a relation. 
User is #<User id: 1, email: "[email protected]" ... etc > 

因此,不知怎的,它似乎忽略了我在那裏的if條件中的logger語句,但運行了賦值。我無法弄清楚爲什麼會發生這種情況 - 有什麼想法?

+0

你是如何得到current_user的價值的? – nbirla 2014-09-23 16:06:14

回答

2
current_user = current_user.first 

這會創建一個局部變量,該局部變量影響current_user方法。局部變量在分析器注意到它們被聲明時立即創建,而不管分配是否實際執行,因此如果if條件爲false,則聲明局部變量current_user並且聲明nil。您需要執行current_user=方法:

self.current_user = current_user.first 

如果您沒有這樣的方法,請定義它。

+0

太棒了!這確實是解決方案。謝謝。 – glenatron 2014-09-23 16:35:30