Ruby on rails 使用“时按两个表中的列排序”;包括「;rubyonrails中的子句

Ruby on rails 使用“时按两个表中的列排序”;包括「;rubyonrails中的子句,ruby-on-rails,sorting,join,Ruby On Rails,Sorting,Join,我有上述包含条款。我在Account表中有两个字段F1,在MonthForecast表中有两个字段F2。我需要按这两个字段对上述结果进行排序 Account.includes(:month_forecasts) .where(month_forecasts: { field: :value }) 我知道上面的内容将按F1排序,但由于F2在MonthForecast表中,我不知道如何按该字段排序。只需将字段名用作字符串即可 Account.includes(:month_forecasts

我有上述
包含
条款。我在
Account
表中有两个字段
F1
,在
MonthForecast
表中有两个字段
F2
。我需要按这两个字段对上述结果进行排序

Account.includes(:month_forecasts)
   .where(month_forecasts: { field: :value })

我知道上面的内容将按
F1
排序,但由于
F2
MonthForecast
表中,我不知道如何按该字段排序。

只需将字段名用作字符串即可

Account.includes(:month_forecasts)
   .where(month_forecasts: { field: :value }).order(:f1)
注意,您需要使用
左外联接
(或者
联接
,如果您不想看到没有预测的帐户),而不是
包含
进行排序

更新:

默认情况下,它只选择
帐户。*
,但您可以添加一个包含第二个表中所有列的select

Account.left_outer_joins(:month_forecasts)
  .where(month_forecasts: { field: :value }).order('f1, month_forecasts.f2')

只需使用字段名作为字符串

Account.includes(:month_forecasts)
   .where(month_forecasts: { field: :value }).order(:f1)
注意,您需要使用
左外联接
(或者
联接
,如果您不想看到没有预测的帐户),而不是
包含
进行排序

更新:

默认情况下,它只选择
帐户。*
,但您可以添加一个包含第二个表中所有列的select

Account.left_outer_joins(:month_forecasts)
  .where(month_forecasts: { field: :value }).order('f1, month_forecasts.f2')

我会使用
joins
进行关联,如果与
month\u predicts
的关联不适用于所有数据,那么它将只具有相关的结果链接。另外,请保留
顺序中描述的字段,以便下次阅读

Account.left_outer_joins(:month_forecasts).select('accounts.*, month_forecasts.*')
  .where(month_forecasts: { field: :value }).order('f1, month_forecasts.f2')

我会使用
joins
进行关联,如果与
month\u predicts
的关联不适用于所有数据,那么它将只具有相关的结果链接。另外,请保留
顺序中描述的字段,以便下次阅读

Account.left_outer_joins(:month_forecasts).select('accounts.*, month_forecasts.*')
  .where(month_forecasts: { field: :value }).order('f1, month_forecasts.f2')

谢谢你的回复<代码>左\u外部\u联接
似乎仅从左表中拾取字段。我需要两个表中的所有字段;如何实现这一点?@Biju一个在联接表上带有条件的外部联接是一个内部联接,因此
帐户。包括(:month\u predicts)。其中(month\u predicts:{field::value})。顺序('f1,month\u predicts.f2')
很好。注意,您需要使用左外部联接(如果不想看到没有预测的帐户,则使用联接)“而不是包含排序”是不正确的
includes
在“includes”关系上带有where条件会创建一个“内部联接”,并将在1个查询中加载关系数据。感谢您的回复<代码>左\u外部\u联接
似乎仅从左表中拾取字段。我需要两个表中的所有字段;如何实现这一点?@Biju一个在联接表上带有条件的外部联接是一个内部联接,因此
帐户。包括(:month\u predicts)。其中(month\u predicts:{field::value})。顺序('f1,month\u predicts.f2')
很好。注意,您需要使用左外部联接(如果不想看到没有预测的帐户,则使用联接)“而不是包含排序”是不正确的
includes
在“includes”关系上使用where条件创建“内部联接”并且将立即加载1个查询中的关系数据基于OP的注释,他希望
MonthForecast
对象也立即加载,因此将
join
切换到
includes
将根据OP的注释解决此问题,他希望
MonthForecast
对象也立即加载,因此切换
连接到
包含将解决此问题