jmccartie
jmccartie

Reputation: 4976

Rails: List of categories where related items count is greater than 0

Rails model: Categories have items

Trying to get a list of categories that actually have items.

Something like:

@categories = Category.where(category.items.count > 0).all

Thanks!

Upvotes: 2

Views: 1851

Answers (2)

mark
mark

Reputation: 10574

Rails 3?

Category.joins(:items).select('distinct categories.*')

should work.

Upvotes: 7

Jon Gauthier
Jon Gauthier

Reputation: 25592

I don't have access to a terminal right now, so I can't test this.. but I think it should work:

Items.find(:all).categories.uniq

This will return any category which is associated with an Item object (so, items.count > 0).

Upvotes: 0

Related Questions