如何在Ruby on Rails中加入ActiveRecord查询中的间接关联?
在我的Ruby on Rails应用程序中,我有一个模型Instance
属于另一个模型Zone
。 Zone
模型本身属于Country
模型。 我正在获取一组Instance
对象,如下所示:
scope :thisweek, -> { joins(:zone).where(zones: {created_at: ...}).includes(:zone)
我想将Country
加入Zone
和Instance
,然后根据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
始终使用表的名称,但includes
/ joins
使用模型中声明的关系名称。