Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - query a has_many association

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.

like image 715
Alex Avatar asked Oct 12 '25 11:10

Alex


1 Answers

I ended up using:

Store.joins(:items).group('items.store_id').having("max(items.name) = 
  min(items.name) and min(items.name) = 'shirt'")
like image 122
Alex Avatar answered Oct 15 '25 03:10

Alex