开发者

Named_scope at least one in has_many association

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜