检索关联对象的属性

时间:2016-09-29 14:37:39

标签: ruby-on-rails

我的帖子有很多评论。评论有正文和标题

 => #<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>

在上面的代码中,您可以看到我尝试从具有注释的帖子中获取body属性,但是我得到了一个no方法异常。如何在这些类型的情况下检索关联的对象数据?

1 个答案:

答案 0 :(得分:1)

1)您收到错误是因为您在注释集合上调用了body,而不是Comment类的单个实例。

2)让它运转起来:

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

Post.first.comments是一个集合,您可以将其视为一个数组并将其映射,例如,以获取所有注释的正文:

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

请务必仔细阅读例外消息。