Rails join query with array of children : get corresponding parents with "ALL" children, not "ANY"

Viewed 75

I have this ActiveRecord query that gives me posts that contain any of the tags listed in tag_ids :

Post.joins(:tags).where(tags: { id: tag_ids })

Is there something I can to become exclusive instead of inclusive ? I want only posts that match all tags in tag_ids.

I'm using Postgres, and looking maybe at doing it through arel ?

Thanks !

1 Answers

Try this:

Post.joins(:tags).where(tags: { id: tag_ids}).group(:id).having("COUNT(DISTINCT tags.id) = #{tag_ids.count}")
Related