You could scope them like so:
class Program
has_many :program_age_groups
has_many :age_groups, through: :program_age_groups
has_many :program_locations
has_many :locations, through: :program_locations
scope :by_age_group,->(age_group){
program_ids = program_age_groups.where(age_group: age_group).pluck(:program_id)
where(id: program_ids)
}
scope :by_location,->(location){
program_ids = program_locations.where(location: location).pluck(:program_id)
where(id: program_ids)
}
end
Then call with
age_groups = ['0-2']
Program.by_age_group(age_groups)
This will return an ActiveRecord::Relation[]
of Program
s with the specified age groups.
Or
location = "Some location"
age_groups = ['0-2']
Program.by_location(location).by_age_group(age_groups)
scopes
are a very powerful tool and I find them especially useful for searching as you can chain them together nicely while preserving readability.
Update
class ProgramLocation
belongs_to :program
belongs_to :location
scope :by_age_group,->(age_group){
program_ids = Program.by_age_group(age_group).pluck(:id)
where(program_id: program_ids)
}
scope :by_location,->(location){
location_ids = Location.where(name: location).pluck(:id)
where(location_id: location_ids
}
end
This assumes that your location as an attribute name
that you are searching for in the scope not sure if this is true but should get you somewhere close.