Query records through its belongs_to relation in Rails

北城余情 提交于 2020-01-28 04:07:55

问题


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 within a scope?


回答1:


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.




回答2:


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's a belongs_to relationship
  • it is locations (plural) in where(…) because it's 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" })



回答3:


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')


来源:https://stackoverflow.com/questions/14116122/query-records-through-its-belongs-to-relation-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!