我怎么能按几列排序?

时间:2014-08-17 05:37:55

标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-3.2

我写了这样的范围

/models/code.rb

scope :recent, lambda { |n = 10| includes(:user).where('users.deleted_at' => nil).order("users.last_active_at DESC").limit(n) }

但是,有时记录中的 users.last_active_at 相同。

所以我尝试在下面添加 created_at DESC

scope :recent, lambda { |n = 10| includes(:user).where('users.deleted_at' => nil).order("users.last_active_at DESC, created_at DESC").limit(n) }

但是我收到了这个错误。我的代码出了什么问题?实际上,代码表中有一个名为 created_at 的列。

Error (Mysql2::Error: Unknown column 'created_at' in 'order clause'

1 个答案:

答案 0 :(得分:1)

由于include决定用户是否在一个SQL查询中加入了代码表,或者生成了2个单独的查询(出于性能原因),您应该确保您引用的是users表及其created_at列:

    scope :recent, lambda { |n = 10| includes(:user).
      where('users.deleted_at' => nil).
      order("users.last_active_at DESC, users.created_at DESC").
      limit(n) }

还可以考虑合并范围以了解责任原因,您可以在此处阅读: Merge your ActiveRecord scopes