【问题标题】:How to join an indirect association in ActiveRecord query in Ruby on Rails?如何在 Ruby on Rails 的 ActiveRecord 查询中加入间接关联?
【发布时间】:2015-03-18 16:00:02
【问题描述】:

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

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

我想将Country 加入ZoneInstance,然后根据zone.country.name 字段对结果集Instance 进行排序。谁能帮帮我?

【问题讨论】:

标签: ruby-on-rails ruby activerecord rails-activerecord


【解决方案1】:

您可以尝试以下方法:

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 始终使用表的名称,但 includes/joins 使用模型中声明的关系名称。

【讨论】:

  • 很高兴知道。感谢您的帮助。
  • 您在最后添加的那一点是实时节省的。多么令人困惑……尽管我确信以这种方式设计它是有正当理由的。
猜你喜欢
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多