开发者

Rails 3.1 Mongoid has_secure_password

开发者 https://www.devze.com 2023-04-09 07:17 出处:网络
I\'m attempting to get has_secure_password to play nice with mongoid. I\'m following Railscasts #270, however when I to signin with a username/password, I get the error:

I'm attempting to get has_secure_password to play nice with mongoid. I'm following Railscasts #270, however when I to signin with a username/password, I get the error:

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 s开发者_如何学Ctill get the same error.

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

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

Option 2: In your model, you should define

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


Mongoid doesn't support the find_by_attribute methods.

You should better use where instead:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号