开发者

results from find_by_email executed in function differs from console

I'm new to Rails and i'm currently learning from tutorials from http://ruby.railstutorial.org/chapters/modeling-and-viewing-users-one#top

find_by_email works on console, however, when I execute find_by_email on User.authenticate("test@test.com","testing") I get a nil returned

Where have I possibly gone wrong ?

Below is part of the codes from my model, User.rb

class User < ActiveRecord::Base
  attr_accessor   :password
  attr_accessible :name, :email, :password, :password_confirmation

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :name,     :presence      => true, 
                       :length        => { :maximum => 50 }
  validates :email,    :presence      => true,
                       :开发者_如何学Pythonformat        => { :with => email_regex },
                       :uniqueness    => { :case_sensitive => false }

  validates :password, :presence      => true,
                       :confirmation  => true,
                       :length        => { :within => 6..40 }

  before_save :encrypt_password

  # Return true if the user's password matches the submitted password.
  def has_password?(submitted_password)
    # Compare encrypted_password with the encrypted version of
    # submitted_password.
    encrypted_password == encrypt(submitted_password)
  end

  def self.authenticate(email, submitted_password) 
    user = find_by_email(email)
    return nil if user.nil?
    # return nil if user.has_password?(submitted_password)
  end

I have tried User.find_by_email("test@test.com") on rails console, and I was returned with the record on my local database.


This is actually a problem with your authenticate method. Ruby always returns the value of the last line it executes in a method. Since the last line in your method is:

return nil if user.nil?

This is the same as:

if user.nil?
  return user
end

When your user is correct, the code inside the if does not get executed, but there is still no return value afterwards, so authenticate returns nil regardless. I would try this instead of your return nil if user.nil? line:

return user if user

or if you prefer explicitness:

return user unless user.nil?

or even more explicit:

return user.nil? ? nil : user

As long as you explicitly return the user as the last line, I think everything should be fine.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜