I have a model Email_address which belongs_to a User. And in my User model it says it has_many email_addresses. Consider the following console output:
irb(main):073:0>
b = EmailAddress.find(2)
EmailAddress Load (0.4ms) SELECT email_addresses.* FROM email_addresses WHERE email_addresses.id = 2 LIMIT 1
=> #EmailAddress id: 2, email: "[email protected]", user_id: 2, created_at: "2013-03-06 02:33:40", updated_at: "2013-03-06 02:33:40"
irb(main):074:0>
b.user
User Load (0.1ms) SELECT users.* FROM users WHERE users.id = 2 LIMIT 1
=> #User id: 2, username: "w", created_at: "2013-03-06 02:33:40", updated_at: "2013-03-06 02:33:40"
irb(main):075:0>
b = EmailAddress.where(:email => "[email protected]")
EmailAddress Load (0.1ms) SELECT email_addresses.* FROM email_addresses WHERE email_addresses.email = [email protected]
=> #EmailAddress id: 1, email: "[email protected]", user_id: 1, created_at: "2013-03-05 07:26:56", updated_at: "2013-03-05 07:26:56"
irb(main):076:0>
b.user
NoMethodError: undefined method user for # from /var/lib/gems/1.8/gems/activerecord-3.2.11/lib/active_record/relation/delegation.rb:45:in `method_missing' from (irb):76
Can someone tell me why when I use where()
I am unable to then locate the User, but it works when I use find()? This is very confusing output.
EmailAddress.where(:email => "[email protected]")
produces anActiveRecord::Relation
object. try to change that toEmailAddress.where(:email => "[email protected]").first
– jvnill