问题
In my Ruby on Rails application, I have a model Instance which belongs to another model Zone. The Zone model itself belongs to Country model. I am fetching a set of Instance objects as follows:
scope :thisweek, -> { joins(:zone).where(zones: {created_at: ...}).includes(:zone)
I would like to join Country to Zone and Instance as well, and then sort the result Instance set based on the zone.country.name field. Anyone can help me please?
回答1:
You can try the following:
scope :this_week, proc do
includes(zone: :country)
.where(zones: {created_at: whatever})
.order('countries.name ASC')
end
(I used the do/end format on purpose to show on multi-lines each instruction)
Also, something you should know:
# if
Zone belongs_to :country
# then
Zone.includes(:country).where(countries: { id: 12 })
# ^ ^^
# but if
Zone has_many :countries
# then
Zone.includes(:countries).where(countries: { id: 12 })
# ^^ ^^
The where always uses the table's name but includes/joins uses the relation's name as it was declared in the model.
来源:https://stackoverflow.com/questions/29126855/how-to-join-an-indirect-association-in-activerecord-query-in-ruby-on-rails