2017-04-15 47 views
0

當我做@post = Post.first.comments.build(content: "bla", user: @user)並通過@user.comments搜索沒有顯示出來。但是當我使用@post.comments時,它會列出評論。我如何能看到我對@user.comments@post.comments的評論?Rails 5:如何通過2個模型查看模型?

class Post < ApplicationRecord 
    belongs_to :user 
    has_many :comments  
end 

我的用戶模型

class User < ApplicationRecord 
    has_many :posts 
    has_many :comments 
end 

評論模型

class Comment < ApplicationRecord 
    belongs_to :user 
    belongs_to :post 
end 
+0

'.build'只是實例化一條新記錄 - 它不會將記錄保存到數據庫。它是'.new'的別名。所以當你執行'@ user.comments'時,它會查詢數據庫,而不關心你在內存中創建的新記錄。 – max

+2

'@comment = Post.first.comments.create(content:「bla」,user:@user); @comment == @ user.comments.last'另一方面將完成你正在尋找的東西。 – max

+0

thx @max它的工作原理,但不知道爲什麼'建立'沒有工作 – chaosfirebit

回答

0

使用through獲得與用戶的帖子相關聯的所有帖子的評論。

class User 
    has_many :posts 
    has_many :comments, through: :posts 
end