Reputation: 2966
Suppose we have a Tag
model with many associated Post
(or none) via a has_many
association.
Is there an efficient way to select only the tags that do have a tag.posts.size > 0
via a scope ?
Something that would behave as follows:
scope :do_have_posts, -> { where("self.posts.count > 0") } #pseudo-code
Thanks.
Upvotes: 0
Views: 52
Reputation: 29349
This should only return you the tags with posts since rails does an inner join by default
scope :with_posts, -> { joins(:posts).uniq }
Upvotes: 2