Query records through its belongs_to relation in Rails

后端 未结 3 1878
悲&欢浪女
悲&欢浪女 2020-12-14 02:06

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

3条回答
  •  时光取名叫无心
    2020-12-14 02:58

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

提交回复
热议问题