Question

A column in my events table contains a column with values like "Hold", "Important", "Pending", etc. I want to return query results to a client and sort by this column, but I do not want to sort alphabetically. "Important" events should be first, "Pending" second, etc. More importantly, I want to return the integer sort value to the client.

@work = Transaction.
     joins( :events ).
     where( store_id: params[:work_id] ).
     where( status: 'Open' )
Was it helpful?

Solution

You can do it like this:

@work = Transaction.
     joins(:events).
     where(store_id: params[:work_id]).
     where(status: 'Open').
     select("(case when your_column = 'Important' then '1' 
                   when your_column = 'Pending' then 2 
                   when your_column = 'Hold' then 3 else 4 end) as your_integer_column").
     order("your_integer_column")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top