Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 still 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.

like image 748
Hinchy Avatar asked Sep 30 '11 11:09

Hinchy


1 Answers

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
like image 75
yfeldblum Avatar answered Sep 20 '22 23:09

yfeldblum