Ruby on rails 如何按特定优先级对activerecord查询排序

Ruby on rails 如何按特定优先级对activerecord查询排序,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,我使用的是rails 3和postrges 我想按特定的优先顺序订购 比如: Assignment.order(priority: ['best', 'good', 'bad']) 这将首先返回所有activerecords,然后返回'best','good','bad' 我似乎找不到像这样的东西。我不需要数组,它必须是activerecords。顺序可以是任何SQL代码。您可以使用CASE语句将值映射到按正确顺序自然排序的值 Assignment.order(" CASE

我使用的是rails 3和postrges

我想按特定的优先顺序订购

比如:

Assignment.order(priority: ['best', 'good', 'bad'])
这将首先返回所有activerecords,然后返回'best','good','bad'


我似乎找不到像这样的东西。我不需要数组,它必须是activerecords。

顺序可以是任何SQL代码。您可以使用
CASE
语句将值映射到按正确顺序自然排序的值

Assignment.order("
    CASE
      WHEN priority = 'best' THEN '1'
      WHEN priority = 'good' THEN '2'
      WHEN priority = 'bad' THEN '3'
    END")
更好的是,您可以将此逻辑移动到模型中,以便更容易从控制器调用:

class Assignment < ActiveRecord::Base
  ...
  def self.priority_order
    order("
        CASE
          WHEN priority = 'best' THEN '1'
          WHEN priority = 'good' THEN '2'
          WHEN priority = 'bad' THEN '3'
        END")
  end
end

然后,您将调用
Assignment.priority\u order(params[:direction])
以从控制器传递排序。

在较新版本的Rails中,您将得到一个
ActiveRecord::UnknownAttributeReference(如果将原始SQL传递给
.order()
,则使用非属性参数调用查询方法)
错误

您需要使用
Arel.SQL()
包装SQL查询。您还可以使用ruby语法编写多行SQL语句,并使其在控制台中更具可读性

所以整个事情变成了:

Assignment.order(
  Arel.sql(<<-SQL.squish
    CASE
      WHEN priority = 'best' THEN '1'
      WHEN priority = 'good' THEN '2'
      WHEN priority = 'bad' THEN '3'
    END
  SQL
  )
)
Assignment.order(
Arel.sql(
Assignment.order(
  Arel.sql(<<-SQL.squish
    CASE
      WHEN priority = 'best' THEN '1'
      WHEN priority = 'good' THEN '2'
      WHEN priority = 'bad' THEN '3'
    END
  SQL
  )
)