【问题标题】:How to order by an associated model in Rails 4, and specify a direction?如何在 Rails 4 中按关联模型排序,并指定方向?
【发布时间】:2026-01-18 23:55:02
【问题描述】:

在 Rails 3.2.17 中,我可以有以下内容:

scope :sorted, -> { joins(:other).order({:other => :code}, :code) }

这会产生以下 SQL:

SELECT [things].* FROM [things] INNER JOIN [others] ON [others].[id] = [things].[other_id] ORDER BY [others].[code] ASC, [things].[code] ASC

但是,Rails 4.0.4 中的相同代码会出现以下错误:

Direction should be :asc or :desc

但是,我想不出一种方法来保持顺序并指定直接。例如,下面的范围给出了相同的错误:

scope :sorted, -> { joins(:other).order({:other => {:code => :asc}}, :code => :asc) }

编辑:明确地说,我想使用哈希样式语法,不想编写原始 SQL 字符串

【问题讨论】:

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


【解决方案1】:

这看起来像是 Rails 4.0+ 中的一个错误(关于order 接受嵌套哈希)

我找到了一个Github issue 供您解释问题

他们建议使用source:,但这仅用于关联声明。如果您找到答案,我很乐意将其删除,但希望对您有所帮助!

【讨论】:

  • 感谢 Rich,通过您的链接,我找到了 PR。我添加了一条评论,但目前看来,这种行为似乎不受支持。很烦人!