Query records through its belongs_to relation in Rails

后端 未结 3 1863
悲&欢浪女
悲&欢浪女 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:46

    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.

    0 讨论(0)
  • 2020-12-14 02:57

    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')
    
    0 讨论(0)
  • 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" })
    
    0 讨论(0)
提交回复
热议问题