Here's some context - let's say I have the following relationships:
class Session < ActiveRecord::Base
has_many :events
end
class Event < ActiveRecord::Base
belongs_to :session
has_many :event_attributes
end
class EventAttribute< ActiveRecord::Base
belongs_to :event
end
And here is the migration for the event attributes table:
create_table :event_attributes do |t|
t.string :key
t.string :value
t.integer :event_id
end
Now the problem - If I have all the events that belong to a session, like so:
session = Session.find(1)
events = session.events
How do I find events that have:
An event_attribute where the key column is 'name' and the value column is 'Bill'
AND
An event_attribute where the key column is 'city' and the value column is 'Seattle'
I tried something like this:
events.includes(:event_attributes)
.where(event_attributes: { key: 'name', value: 'Bill' })
.where(event_attributes: { key: 'city', value: 'Seattle' })
This provides 0 results. If I query a single where condition I get the expected result, I'm just not sure how to search on a collection with multiple conditions on the has_many association.