Reputation: 808
I can't find query interface from Active Record to show only categories that have at least one product. how to do that?
category.rb
class Category < ActiveRecord::Base
has_many :products
end
product.rb
class Product < ActiveRecord::Base
belongs_to :category
end
thank you
Upvotes: 1
Views: 547
Reputation: 808
@categories = Category.joins(:products).where('products.id is not null').group('products.category_id')
it will show only category that have at least one product.
Upvotes: 1
Reputation: 17834
You can do this
@categories = Category.joins(:products).where('categories.id is not null').group('products.id')
Upvotes: 0