【问题标题】:How can I sort by few columns?如何按几列排序?
【发布时间】:2014-08-17 05:37:55
【问题描述】:

我这样写范围

/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'

【问题讨论】:

  • 如果您想要的是userscreated_at,则使用users.created_at DESC 而不是created_at DESC。如果是codes,则使用codes.created_at DESC

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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 2010-12-14
    • 2013-09-08
    • 2013-04-11
    相关资源
    最近更新 更多