0
votes

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.

1
EmailAddress.where(:email => "[email protected]") produces an ActiveRecord::Relation object. try to change that to EmailAddress.where(:email => "[email protected]").firstjvnill
Bingo! Thank you jvnill! That works perfectly.user985723
Try to use "scope" as much as possible instead of using "where" in your controller, coz it makes the code more readable/maintainable. Read more about scopes here guides.rubyonrails.org/active_record_querying.html#scopessameera207

1 Answers

3
votes

.where() returns an array (specifically ActiveRecord::Relation). To select the returned objects you'd need to specify which object. In this case, since you're expecting one object you can do:

b = EmailAddress.where(:email => "[email protected]").first

OR

b = EmailAddress.where(:email => "[email protected]")[0]