2013-08-23 42 views
2

會話控制器:無法調用.authenticate方法has_secure_password

class SessionsController < ApplicationController 
    def new 
    end 

    def create 
    user = User.find_by_email(params[:email]) 
    if user && User.authenticate(params[:password]) 
     session[:user_id] = user.id 
     redirect_to products_path, notice: 'Logged in successfully' 
    else 
     flash.now.alert = "Email or password is invalid" 
     render 'new' 
    end 
    end 

    def destroy 
    end 
end 

用戶模式:在形式上

class User < ActiveRecord::Base 
    has_secure_password 

    attr_accessible :email, :password, :password_confirmation 

    validates_uniqueness_of :email 
end 

登錄:

<h1>Login form</h1> 

<%= form_tag sessions_path do %> 

    <%= label_tag :email %><br/> 
    <%= text_field_tag :email, params[:email] %><br/> 

    <%= label_tag :password %><br/> 
    <%= password_field_tag :password, params[:password] %><br/> 

    <%= submit_tag "Login" %> 
<% end %> 

當我嘗試使用我的登錄表單NoMethodError被提出,說明authenticate未定義。

我認爲通過將has_secure_password放在用戶模型中提供了驗證方法?我錯了嗎?

任何幫助表示讚賞!

+0

我得到了我的代碼從視頻(#250)的修訂版試玩。但我使用Rails 3.2而不是3.1。 – Kane

回答

3

我相信你需要的用戶對象上進行身份驗證,這個

def create 
    user = User.find_by_email(params[:email]) 
    if user && user.authenticate(params[:password]) 
     session[:user_id] = user.id 
     redirect_to products_path, notice: 'Logged in successfully' 
    else 
     flash.now.alert = "Email or password is invalid" 
     render 'new' 
    end 
    end 
+1

欲瞭解更多信息,請參閱 - http://www.millwoodonline.co.uk/blog/using-hassecurepassword-for-rails-authentication –

+0

如果我們已安裝設計寶石,此方法不再有效 –