Rails 3.1 Mongoid has_secure_password

Rails 3.1 Mongoid has_secure_password

我正试图让has_secure_password与蒙古人玩得很好。我正在关注Railscasts#270,但是当我使用用户名/密码登录时,出现错误:

1
undefined method `find_by_email' for User:Class

不过,我看到了类似的帖子(http://stackoverflow.com/questions/6920875/mongoid-and-has-secure-password),因为这样做表明我仍然遇到相同的错误。

这是我的模特:

1
2
3
4
5
6
7
8
9
10
11
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

控制器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

谢谢。


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

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

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

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

Mongoid不支持find_by_attribute方法。

您最好改用where

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