junior
junior

Reputation: 808

Rails Active Record how to check associated record not empty

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

Answers (2)

junior
junior

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

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You can do this

@categories = Category.joins(:products).where('categories.id is not null').group('products.id')

Upvotes: 0

Related Questions