Custom order based on Enum values

I have an Enum value for roles:

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

I would like to order a collection of objects in the following order:

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

Is this even possible?

+6
source share
2 answers

The solution for this:

 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 

Then your request will be simple:

 YourModel.order_by_role 

Generated Request:

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

Nice link from this

+7
source

Thanks to this answer, I came up with the following:

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

Or, as an area with optional arguments:

 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") } 
0
source

All Articles