开发者

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("someaddress@email.com开发者_高级运维")

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("someaddress@email.com", "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.


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.


Did you check the email's value before calling find_by_email? Maybe it has an invalid space in it, so check the sql log and copy it to dbconsole.


This method would return nil if either:

  • There was no user object (unlikely, since find_by_email works in the console)
  • If has_password? returns false, which is likely.

Check your has_password? method is doing the right thing.


I found the answer guys ... thanks so much for jumping in and suggesting some solution.

I had another method that I didn't include in the code above that was the "real" issue.

As for my original question it turns out that the method was working. I had typo in the string that I was passing to the method. Basically I left the ".com" off the end of the email.

As usually a simple typo makes me feel really dumb for posting the question but over all thinking though the problem and looking at your suggestions helped me find the solution so thanks so much.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜