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

moo*_*ara 3 ruby activerecord ruby-on-rails rails-activerecord

在Ruby on Rails应用程序中,我有一个模型Instance属于另一个模型Zone。该Zone模型本身属于Country模型。我正在获取一组Instance对象,如下所示:

scope :thisweek, -> { joins(:zone).where(zones: {created_at: ...}).includes(:zone)
Run Code Online (Sandbox Code Playgroud)

我想加盟Country,以ZoneInstance为好,然后排序结果Instance基础上设定的zone.country.name领域。有人可以帮我吗?

MrY*_*iji 5

您可以尝试以下方法:

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

(我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 })
#                     ^^               ^^
Run Code Online (Sandbox Code Playgroud)

where总是使用表的名称,但includes/ joins使用关系的名字,因为它是在模型中声明。