I have a User model that has_many开发者_如何学Go :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"
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
加载中,请稍侯......
精彩评论