如何在 Ruby on Rails 的 ActiveRecord 查询中加入间接关联?

How to join an indirect association in ActiveRecord query in Ruby on Rails?

在我 Ruby 关于 Rails 的申请中,我有一个模型 Instance 属于另一个模型 ZoneZone 模型本身属于 Country 模型。我正在获取一组 Instance 个对象,如下所示:

scope :thisweek, -> { joins(:zone).where(zones: {created_at: ...}).includes(:zone)

我也想加入CountryZoneInstance,然后根据zone.country.name字段对结果Instance集合进行排序.有人可以帮我吗?

您可以尝试以下方法:

scope :this_week, proc do
  includes(zone: :country)
    .where(zones: {created_at: whatever})
    .order('countries.name ASC')
end

(我特意用了do/end的格式来多行显示每条指令)


还有一些你应该知道的:

# 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 })
#                     ^^               ^^

where 始终使用 table 的名称,但 includes/joins 使用模型中声明的关系名称。