2012-08-04 49 views
3

這裏查詢有點複雜。三個相關的表格:用戶,帖子和評論。用戶has_many帖子和評論,帖子屬於用戶和has_many評論,評論屬於用戶和帖子。也就是說,我在Rails中試圖在我的控制器中查找用戶在他所有帖子中收到的所有評論。我試過這個:rails找到帖子的所有評論user_id = user

@comments = Comment.where(:post_id.user => @user.id) 

但這並沒有真正解決。這可能是一個簡單的解決方案,幫助?

+0

這可以幫助你知道你能不能做:) HTTP ://guides.rubyonrails.org/active_record_querying.html – 2012-08-04 04:49:18

回答

6

你必須join該職位表:

@comments = Comment.joins(:post).where(:posts => { :user_id => @user.id }) 
+0

真棒,謝謝。 – user1152706 2012-08-04 04:47:41

1

你也可以這樣做:

@user = User.find(@user.id, :include => :comments) 

<% @user.comments.each do |comment| %> 
    <%= comment.id %> <br/> 
    <%= comment.text %> 
<% end %> 
+0

這看起來好多了。 – 2013-08-20 18:29:22

+0

@scottastic,它不會做問題,但問題。 – Mischa 2014-04-08 11:30:38

+0

這會獲得用戶提出的評論,而不是用戶在他的帖子上收到的所有評論。 – Mischa 2014-04-08 11:31:13