如何在Ruby on Rails的ActiveRecord查询中加入间接关联? [英] How to join an indirect association in ActiveRecord query in Ruby on Rails?

查看:65
本文介绍了如何在Ruby on Rails的ActiveRecord查询中加入间接关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby on Rails应用程序中,我有一个模型 Instance ,该模型属于另一个模型 Zone 区域模型本身属于 Country 模型。我正在按以下方式获取一组 Instance 对象:

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)

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

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?

推荐答案

您可以尝试以下操作:

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

其中始终使用表名,但 includes / 使用模型中声明的关系名称。

The where always uses the table's name but includes/joins uses the relation's name as it was declared in the model.

这篇关于如何在Ruby on Rails的ActiveRecord查询中加入间接关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆