Ok, so I am new to ruby and rails and it will probably show with my question.
I am writing a for fun app and have a particularly strange question in regards to finding records in a HABTM relationship. The underlying database is Postgresql
My models look like the following
class Family < ActiveRecord::Base
has_and_belongs_to_many :persons
end
class Person < ActiveRecord::Base
has_and_belongs_to_many :families
end
Lets say I have 4 people 'Joe', 'Jane', 'Mary', 'Ben'. They can all belong to multiple families.
Family 1 << 'Joe', 'Jane', 'Ben'
Family 2 << 'Jane', 'Ben'
Family 3 << 'Joe', 'Jane', 'Ben', 'Mary'
I would like to be able to find families by searching for their names
This is what my query currently looks like
Family.joins(:persons).where(persons: {name:['Joe','Jane','Ben']})
This works great at finding all records that either have Joe or Jane or Ben (all the families) but not at returning records that only have Joe, Jane, and Ben.
In my example, I am looking to find only Family 1, not the other 2.
How can I make sure that I am only finding records that have all of the names, no more, no less.
Is there a better query to write or should I rethink my database structure?