Query records through its belongs_to relation in Rails

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)