基于枚举值的自定义顺序

我为角色定义了Enum:

enum role: {ordinary: 0, manager: 1, admin: 2} 

我想按以下顺序订购一组对象:

 admin (first all admins) ordinary (then all ordinaries) manager (and lastly all managers) 

这有可能吗?

解决方案:

 class YourModel < ActiveRecord::Base ROLE_ORDERS = [2, 0, 1] scope :order_by_role, -> { order_by = ['CASE'] ROLE_ORDERS.each_with_index do |role, index| order_by << "WHEN role=#{role} THEN #{index}" end order_by << 'END' order(order_by.join(' ')) } end 

那么你的查询将很简单:

 YourModel.order_by_role 

生成的查询是:

 SELECT * from your_models ORDER BY ( CASE WHEN role=2 THEN 0 WHEN role=0 THEN 1 WHEN role=1 then 2 END ) 

很好的参考

感谢这个回答,我想出了这个:

 order("role = 0 DESC, role = 1 DESC, role = 2 DESC") 

或者,作为具有可选参数的范围:

 scope :order_by_roles, -> (first = :admin, second = :ordinary, third = :manager) { order("role = #{User.roles[first]} DESC, role = #{User.roles[second]} DESC, role = #{User.roles[third]} DESC") }