adamscott
adamscott

Reputation: 853

Retrieving attributes of associated object

I have a post that has many comments. Comments have a body and a title

 => #<ActiveRecord::Associations::CollectionProxy [#<Comment id: 1, author: "jack", body: "how do you like dem apples?", post_id: 1, created_at: "2016-09-29 02:11:00", updated_at: "2016-09-29 02:11:00">]> 
2.3.0 :005 > Post.first.comments
  Post Load (0.5ms)  SELECT  "posts".* FROM "posts"  ORDER BY "posts"."id" ASC LIMIT 1
  Comment Load (0.2ms)  SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ?  [["post_id", 1]]
 => #<ActiveRecord::Associations::CollectionProxy [#<Comment id: 1, author: "jack", body: "how do you like dem apples?", post_id: 1, created_at: "2016-09-29 02:11:00", updated_at: "2016-09-29 02:11:00">]> 
2.3.0 :006 > Post.first.comments.body

NoMethodError:   Comment Load (0.2ms)  SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ?  [["post_id", 1]]
undefined method `body' for #<Comment::ActiveRecord_Associations_CollectionProxy:0x007f9bef0a33a8>

In the code above you can see that I try to get the body attribute from the post that has a comment, but I get a no method exception. How do I retrieve the associated objects data in these types of situations?

Upvotes: 1

Views: 280

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52347

1) You get error because you are calling body on the collection of comments, not a single instance of Comment class.

2) To get it working:

# select the comment, which's body you want to get
Post.first.comments.first.body

Post.first.comments is a collection, you can treat it as an array and map it, for example, to get all comments' bodies:

# would return all bodies of all comments, that belongs to the `Post.first`
Post.first.comments.pluck(:body)

Always read exceptions messages carefully.

Upvotes: 1

Related Questions