2010-11-28 49 views
3

我有一個用戶模型,其中有一個身份驗證方法。軌道動態find_by方法不能在類方法內工作

如果我在rails控制檯中使用模型進行測試,可以創建一個用戶就好了,然後我可以在電子郵件上找到並像這樣完全返回用戶。

user = User.find_by_email("[email protected]") 

現在,如果我嘗試調用這樣的身份驗證方法和返回用戶看跌期權用戶聲明,我的身份驗證方法返回零

user = User.authenticate("[email protected]", "foobar") 

這個模型看起來像這樣

class User < ActiveRecord::Base 

    attr_accessor :password 
    attr_accessible :first_name, :last_name, 
        :email, :birth_date, :sex, 
        :password, :password_confirmation 


    def self.authenticate(email, submitted_password) 
    user = find_by_email(email) 

    puts user #this returns nil so my class is never able to authenticate the user 

    return nil if user.nil? 
    return user if user.has_password?(submitted_password) 
    end 

end 

我對這個問題感到不知所措。對此問題的一些看法將非常感激。

回答

2

您在Class方法中使用find_by方法的方式很好;這應該工作。

你確定零輸出是來自put嗎?零可能是你的方法的輸出。有可能是user.has_password?有錯誤。

相反的puts,請嘗試:

p user 

...只是要確定。

0

您是否在致電find_by_email之前檢查電子郵件的值?也許它有一個無效的空間,所以檢查sql日誌並將其複製到dbconsole。

0

此方法將返回nil如果任:

  • 有沒有用戶對象(不太可能,因爲在控制檯find_by_email作品)
  • 如果has_password?返回false,這是可能的。

檢查您的has_password?方法是否正確。

+0

這是BTW的真正解決方案。我在看到你的建議之前找到了它。好決定。 – mattwallace 2010-11-28 23:52:43

0

我找到了答案的傢伙......非常感謝你的加入並提出了一些解決方案。

我有另一種方法,我沒有在上面的代碼中包含「真正」的問題。

至於我原來的問題,事實證明,該方法工作。我在傳遞給該方法的字符串中存在拼寫錯誤。基本上,我離開了電子郵件結尾的「.com」。

由於通常一個簡單的錯字讓我覺得真的很愚蠢的發佈的問題,但總體思路雖然問題,看着你的建議幫助我找到解決方案,所以非常感謝。