2014-02-15 50 views
3

我在嘗試驗證用戶時收到以下錯誤。Rails - 未定義的方法`驗證'

NoMethodError (undefined method的authenticate」的#)`

user.authenticate( '密碼')是成功的(即返回用戶對象)當我執行從軌道控制檯該命令。

irb(main):008:0> user.authenticate("sanket") 
=> #<User id: 2, name: "Sanket", email: "[email protected]", created_at: "2014-02-14 08:58:28", updated_at: "2014-02-14 08:58:28", password_digest: "$2a$10$KNuBgvqVDIErf3a24lMcaeNt1Hyg0I8oreIQSEYsXY4T...", remember_token: "3b64273a4fcced7c8bf91f7f7490e60a5919658d"> 

然而,當我在一個輔助類把user.authenticate,並使用URL訪問它,它說

undefined method 'authenticate' for #<ActiveRecord::Relation:0x007fd9506dce38>

我下面Rails Tutorial

我的用戶模型看起來像:

class User < ActiveRecord::Base   
    attr_accessible :email, :name, :password, :password_confirmation 
    has_secure_password 

    . 
    . 
    . 
end 

相關製藥OD在session_helper.rb樣子:

def create 
    user = User.where(:email => params[:session][:email].downcase) 

    if user && user.authenticate(params[:session][:password]) 
     sign_in user 
     redirect_to user 
    else 
     flash.now[:error] = 'Invalid email/password combination' 
     render "new" 
    end 
end 

它詳細介紹了if user && user.authenticate(params[:session][:password])線上面的錯誤。

令我驚訝的是,它是從rails控制檯工作的,但是同樣的調用不能從rails服務器上運行。

回答

11

正如你在你的錯誤中看到的,where返回一個關係,而不是一個單一的對象。

檢查相關的問題:Why does a single record lookup return an array? (Rails beginner)

在你的情況,你可以添加first到方法鏈的末端,所以它會返回這個關係的第一要素:

user = User.where(:email => params[:session][:email].downcase).first 
+0

這也解釋了它。謝謝。 –

相關問題