在rails3的连接查询中获取不同的记录

在rails3的连接查询中获取不同的记录

问题描述:

一篇文章有​​很多评论,并且我想获取所有具有评论匹配条件的文章。在rails3的连接查询中获取不同的记录

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

获取重复记录 和

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

也将获取评论数据,我只是想获取uniq的文章数据

您可以尝试使用摹

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

例如你想获取所有文章当前用户的评论

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