Named_scope at least one in has_many association

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

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

or should I take one more step and take

   named_scope :at_least_one_post, :joins => :posts, :group => "users.id", :having => "COUNT(posts.id) > 0"
+3
source share
1 answer

Actually, I don’t think it is necessary to group or add a condition. Since you are using :joins, that will do INNER JOINand therefore will only pull users with messages. If you are going to do: include, it will be LEFT JOIN, and you will need to add a sentence HAVING.

So all you need is

named_scope :at_least_one_post, :joins => :posts
+4
source

Source: https://habr.com/ru/post/1752386/


All Articles