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

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

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

我想将Country加入ZoneInstance ,然后根据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使用模型中声明的关系名称。