I have an Activities model, and they belong_to a Location
How do i select all the activities whose location.country = Australia? (for example)
Can I do this
The kind of query you're talking about is a join. You can try queries like this in the console like:
Activity.joins(:locations).where('locations.country = "Australia"')
This means that SQL is going to take all the activities and locations associated with then, find the locations where country=Australia, and then return you the activities that are associated with those locations.
To make this into a more reusable scope, define it on your model with a variable for country:
scope :in_country, lambda {|country| joins(:locations).where('locations.country = ?',country)}
You can learn more about this in the API docs.
Yes, a scope can be used. Something like this ought to work on the Activities model:
scope :down_under,
joins(:locations).
where("locations.country = 'Australia')
With the latest rails versions you can do:
Activity.joins(:location).where(locations: { country: "Australia" })
Beware:
joins(:location)
because it references the belongs_to
relationship namewhere(…)
because it references the table nameThe latter means that if you had the following:
belongs_to :location, class_name: "PublicLocation"
the query would be:
Activity.joins(:location).where(public_locations: { country: "Australia" })