2011-09-30 95 views
6

我試圖讓has_secure_password和mongoid一起玩。我下面Railscasts#270,但是當我用一個用戶名/密碼簽到,我得到的錯誤:Rails 3.1 Mongoid has_secure_password

undefined method `find_by_email' for User:Class 

我看到了類似的帖子(http://stackoverflow.com/questions/6920875/mongoid但是,按照它的建議,我仍然得到相同的錯誤。

這裏是我的模型:

class User 
    include Mongoid::Document 
    include ActiveModel::SecurePassword 

    validates_presence_of :password, :on => :create 
    attr_accessible :email, :password, :password_confirmation 

    field :email, :type => String 
    field :password_digest, :type => String 
    has_secure_password 
end 

控制器:

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 root_url, :notice => "Logged in!" 
    else 
     flash.now.alert = "Invalid email or password" 
     render "new" 
    end 
    end 

    def destroy 
    session[:user_id] = nil 
    redirect_to root_url, :notice => "Logged out!" 
    end 

end 

感謝。

回答

11

選項1:在你的控制器,你應該使用

user = User.where(:email => params[:email]).first 

選項2:在你的模型,你應該定義

def self.find_by_email(email) 
    where(:email => email).first 
end 
+0

選項2偉大的工作。謝謝! – Hinchy

0

Mongoid不支持find_by_attribute方法。

你應該更好地利用where代替:

User.where(:email => email).all