2012-03-26 42 views
3

一篇文章有​​很多評論,並且我想獲取所有具有評論匹配條件的文章。在rails3的連接查詢中獲取不同的記錄

Article.find(:joins => :comments ...) 

獲取重複記錄 和

Article.find(:include => :comments ...) 

也將獲取評論數據,我只是想獲取uniq的文章數據

回答

9

您可以嘗試使用摹

Article.select("DISTINCT articles.*").joins(:comments).where(...) 

或語法你使用

Article.find(:all, :joins => :comments, :select => 'DISTINCT articles.*' ...) 
+1

謝謝,它會產生相當的sql我想要什麼 – peon 2012-03-26 15:09:54

+0

感謝,它在軌道4,5工作太:d – 2014-06-24 04:50:23

1

例如你想獲取所有文章當前用戶的評論

Article.joins(:comment).where(:comment => {author: current_user.id}).group_by("comments.article_id")