简体   繁体   中英

Named_scope at least one in has_many association

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM