在我的Ruby on Rails应用程序中,我有一个模型Instance
属于另一个模型Zone
。该Zone
模型本身属于Country
模型。我正在获取一组Instance
对象,如下所示:
scope :thisweek, -> { joins(:zone).where(zones: {created_at: ...}).includes(:zone)
我想加盟Country
,以Zone
和Instance
为好,然后排序结果Instance
基础上设定的zone.country.name
领域。有人可以帮我吗?
您可以尝试以下操作:
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
使用关系的名字,因为它是在模型中声明。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句