Find only users who posted at least one comment

I am using Rails 2.3.5.

This is a standard case. Tables: users, comments, user_comments. I need to find all users who have the status "active", and posted at least one comment.

I know that a comment table may have a foreign key, but this is a contrived example. There are two users in the table. There are two comments. Both comments are posted by the first user.

named_scope :with_atleast_one_comment, lambda { { :joins => 'inner join user_comments on users.id = user_comments.user_id ' } } named_scope :with_active_status, {:conditions => {:status => 'active'} } 

When i do

  User.with_atleast_one_comment.with_active_status 

I get two entries. Since both comments are posted by one user, I want only one user.

What is the fix?

+4
source share
3 answers

The with_at_least_one_comment area does not behave as you expected. As the question seems, he will select a user for each entry in user_comments. This leads to duplication of the results that you see. When added with active_users, you delete any entries returned with_at_least_one_comment that do not have an active state.

First, we’ll start by simplifying the problem area. You do not need a lambda, because there are no arguments, and the connection can be outsourced to an active record that performs an internal connection if an association is specified.

In short, this named scope will do exactly what you want.

 named_scope :with_at_least_one_comment, :joins => :user_comments, :group => 'users.id' 
+5
source

Specify the parameter: uniq => true to remove duplicates from the collection. This is most useful in combination with the option: through.

0
source

if I'm not mistaken, there are several ways to achieve this ...
if only User.comments?
or in another way, a new method is also indicated in your controller, and finally ...
info from emfi should work try it ~

0
source

All Articles