简体   繁体   English

Rails 3.1 Mongoid has_secure_password

[英]Rails 3.1 Mongoid has_secure_password

I'm attempting to get has_secure_password to play nice with mongoid. 我试图让has_secure_password与mongoid玩得很好。 I'm following Railscasts #270, however when I to signin with a username/password, I get the error: 我正在关注Railscasts#270,但是当我用用户名/密码登录时,我收到错误消息:

undefined method `find_by_email' for User:Class

I see a similar post (http://stackoverflow.com/questions/6920875/mongoid-and-has-secure-password) however, having done as it suggested I still get the same error. 我看到一个类似的帖子(http://stackoverflow.com/questions/6920875/mongoid-and-has-secure-password)但是,按照它的建议我仍然得到相同的错误。

Here is my model: 这是我的模型:

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

Controller: 控制器:

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

Thanks. 谢谢。

Option 1: In your controller, you should use 选项1:在您的控制器中,您应该使用

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

Option 2: In your model, you should define 选项2:在您的模型中,您应该定义

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

Mongoid doesn't support the find_by_attribute methods. Mongoid不支持find_by_attribute方法。

You should better use where instead: 你应该更好地使用where

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM