views:

30

answers:

1

I have a User model that has_many :posts. If I wanted to make a named_scope for finding users with at least one post would this be correct?

   named_scope :at_least_one_post, :joins => :posts, :group => "users.id"

or should I take it a step further and do

   named_scope :at_least_one_post, :joins => :posts, :group => "users.id", :having => "COUNT(posts.id) > 0"
+2  A: 

Actually I don't think it is necessary to group or add the condition. Because you are using the :joins, that will do an INNER JOIN and will therefore only pull users with posts. If you were going to do an :include, that would LEFT JOIN and you would need to add a HAVING clause.

So all you should need is

named_scope :at_least_one_post, :joins => :posts
Geoff Lanotte
you should leave in the :group, otherwise what happens when there are more than one post for the user? You'll get a whole lot of duplicate user records in your result set because of the INNER JOIN.(unless rails automatically filters that out for you, I forget - even so, why return unnessecary rows from the db?)
dalyons
The ORM takes care of the grouping, even on a `LEFT JOIN`. If you start grouping with the `GROUP BY` statement, then you are going to need to group or aggregate every column in the `SELECT` statement.
Geoff Lanotte
Is there an easy way to find Users with zero posts?
chap