Query records through its belongs_to relation in Rails

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.


With the latest rails versions you can do:

Activity.joins(:location).where(locations: { country: "Australia" })

Beware:

  • it is location (singular) in joins(:location) because it references the belongs_to relationship name
  • it is locations (plural) in where(…) because it references the table name

The 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" })