Reputation: 21
I have a Project object, which has multiple comments.
I can easily get all comments for the project by using @project.comments
However, I would like to filter out all non unique comments for that project.
For instance if there are two comments which both say "Hello world.", I don't want either of them to be in my results.
Also, I want the resulting array to be an array of comment objects not just one attribute of the comment object.
I have currently come up with the following solution
unique_comments_for_project = []
@project.comments.each do |comment|
if @project.comments.where(:text => comment.text).size < 2
unique_comments_for_project << comment
end
end
However, this solution seems to be extremely inefficient. Is there a better Ruby on Rails way of doing this?
N.B. The problem with @project.comments.select('distinct text') is that it provides one of the duplicates in the results. I don't want any duplicates.
Upvotes: 2
Views: 826
Reputation: 22926
Group the comments by text and filter using having clause.
@project.comments.select('text').group('text').having('count(distinct text) = 1')
Upvotes: 2