Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails dynamic find_by method not working within Class method

I have a user model that has an authentication method in it.

If I test out using the Model in the rails console can create a user just fine and then I can do a find on the email and return the user perfectly like this.

user = User.find_by_email("[email protected]")

Now if I try to call the authentication method like this and return the user the puts user statement in my authentication method returns nil

user = User.authenticate("[email protected]", "foobar")

The model looks something like this

  class User < ActiveRecord::Base

  attr_accessor   :password
  attr_accessible :first_name, :last_name,
                  :email, :birth_date, :sex,
                  :password, :password_confirmation


  def self.authenticate(email, submitted_password) 
    user = find_by_email(email) 

    puts user  #this returns nil so my class is never able to authenticate the user

    return nil if user.nil? 
    return user if user.has_password?(submitted_password)
  end

end

I am at a loss for what the issue is. Some in sight into this issue would be very much appreciated.

like image 391
mattwallace Avatar asked Jul 16 '26 14:07

mattwallace


1 Answers

The way you are using the find_by method inside the Class method is fine; that should work.

Are you sure that the nil output is from puts? The nil maybe the output of your method. It's possible that user.has_password? has an error in it.

Instead of puts, try:

p user

... just to be sure.

like image 120
Scott Avatar answered Jul 18 '26 04:07

Scott