I'm having trouble querying a has_many association. The context is stores.
class Store < ActiveRecord::Base
has_many :items
end
class Item < ActiveRecord::Base
belongs_to: store
end
Stores table:
id name
1 Macys
2 Target
3 Dillards
Items table:
id store_id name
1 1 pants
2 1 shirt
3 2 pants
4 2 shirt
5 3 shirt
I'm trying to query for stores that only sell shirts. So I need a query that returns the store
record with id
of 3
.
When I tried to do
Store.includes(:items).where(
items: { name: %w(shirts)} ).references(:items)
it returns store_ids
1, 2, and 3 (all stores) because they all have shirts.
I ended up using:
Store.joins(:items).group('items.store_id').having("max(items.name) =
min(items.name) and min(items.name) = 'shirt'")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With