Rails 3.1 Mongoid has_secure_password
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
精彩评论