peon
peon

Reputation: 1883

fetch distinct record in a join query in rails3

one Article has many Comments, and i want to fetch all Articles that have Comments match a condition.

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

fetch the duplicate records and

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

will also fetch the Comment data,I just want to fetch the uniq Article data

Upvotes: 3

Views: 3455

Answers (2)

Pavel S
Pavel S

Reputation: 1543

You can try using

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

or with syntax you're using

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

Upvotes: 9

fl00r
fl00r

Reputation: 83680

For example you are trying to fetch all articles with current user's comments

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

Upvotes: 1

Related Questions