2016-09-29 95 views
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 :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> 

在上面的代碼中,你可以看到,我試圖從具有註釋後身體屬性,但我得到一個沒有方法例外。如何在這些類型的情況下檢索關聯的對象數據?

回答

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) 

請務必仔細閱讀例外信息。

+0

謝謝安德烈! – adamscott