0

I'm totally confused. I'm learning Rails 4 and this returns user records as expected:

irb(main):002:0> User.all

But this returns nil

irb(main):004:0> User.authenticate('asdfdsf', 'asdfdas')

Here's the class method in the model:

def self.authenticate( email, password )
    user = User.all #( email: email )
    puts user
    # if user && (user.hashed_password == User.hash_with_salt( password, user.salt ) )
    #   return user
    # else
    #   return false
    # end
end

Am I missing something? Shouldn't these both return the same thing? Why can't I return a user object with .find() or .where() from inside a class method?

Update: Here's the schema of my users table:

  create_table "users", force: true do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.string   "email"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "hashed_password"
    t.string   "salt"
  end
auselen
  • 27,577
  • 7
  • 73
  • 114
emersonthis
  • 32,822
  • 59
  • 210
  • 375

1 Answers1

1

No. It would if there wasn't puts user line. puts call returns nil and it's returned from whole method as a last evaluated value.

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
  • Thanks. I'm returning the object now. But I'm confused because when I try to call one of it's methods... `u = User.authenticate.first; u.hashed_password` , I get an undefined method error: `undefined method 'hashed_password'` – emersonthis Aug 27 '13 at 19:43
  • @Emerson did you run your migration? What is your db schema? – Marek Lipka Aug 27 '13 at 19:46
  • I added it to the question. I notice there's no index. Does that matter? – emersonthis Aug 27 '13 at 19:53
  • @Emerson whad does `User.new.hashed_password` return? – Marek Lipka Aug 27 '13 at 19:56
  • If I do `u = User.find(1)` I get a user object back with a long string in place for the `salt: ` but when I immediately afterwards do `u.salt` I get `nil` – emersonthis Aug 27 '13 at 20:06
  • I figured it out. I had accidentally redeclared `attr_accessor :hashed_password` and it was creating weirdness. – emersonthis Aug 27 '13 at 20:11