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>
在上面的代碼中,你可以看到,我試圖從具有註釋後身體屬性,但我得到一個沒有方法例外。如何在這些類型的情況下檢索關聯的對象數據?
謝謝安德烈! – adamscott