這裏查詢有點複雜。三個相關的表格:用戶,帖子和評論。用戶has_many帖子和評論,帖子屬於用戶和has_many評論,評論屬於用戶和帖子。也就是說,我在Rails中試圖在我的控制器中查找用戶在他所有帖子中收到的所有評論。我試過這個:rails找到帖子的所有評論user_id = user
@comments = Comment.where(:post_id.user => @user.id)
但這並沒有真正解決。這可能是一個簡單的解決方案,幫助?
這裏查詢有點複雜。三個相關的表格:用戶,帖子和評論。用戶has_many帖子和評論,帖子屬於用戶和has_many評論,評論屬於用戶和帖子。也就是說,我在Rails中試圖在我的控制器中查找用戶在他所有帖子中收到的所有評論。我試過這個:rails找到帖子的所有評論user_id = user
@comments = Comment.where(:post_id.user => @user.id)
但這並沒有真正解決。這可能是一個簡單的解決方案,幫助?
你必須join該職位表:
@comments = Comment.joins(:post).where(:posts => { :user_id => @user.id })
真棒,謝謝。 – user1152706 2012-08-04 04:47:41
你也可以這樣做:
@user = User.find(@user.id, :include => :comments)
<% @user.comments.each do |comment| %>
<%= comment.id %> <br/>
<%= comment.text %>
<% end %>
這可以幫助你知道你能不能做:) HTTP ://guides.rubyonrails.org/active_record_querying.html – 2012-08-04 04:49:18