ruby-on-rails – Rails 3.1 Mongoid has_secure_password

我试图让has_secure_password与mongoid玩得很好.我正在关注Railscasts#270,但是当我用用户名/密码登录时,我收到错误
undefined method `find_by_email' for User:Class

我看到一个类似的帖子(https://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

谢谢.

解决方法

选项1:在您的控制器中,您应该使用
user = User.where(:email => params[:email]).first

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

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...