Rails 3.1 Mongoid has_secure_password

时间:2011-09-30 11:36:48

标签: ruby-on-rails ruby-on-rails-3.1 mongoid

我试图让has_secure_password与mongoid玩得很好。我正在关注Railscast#270,但是当我用用户名/密码登录时,我收到错误:

undefined method `find_by_email' for User:Class

我看到一篇类似的帖子(http://stackoverflow.com/questions/6920875/mongoid-and-has-secure-password)但是,按照它的建议我仍然会得到同样的错误。

这是我的模特:

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

感谢。

2 个答案:

答案 0 :(得分:11)

选项1:在您的控制器中,您应该使用

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

选项2:在您的模型中,您应该定义

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

答案 1 :(得分:0)

Mongoid不支持find_by_attribute方法。

您应该更好地使用where

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