Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort activerecord query by specific prority

I am using rails 3 and postrges.

I would like order by a specific priority.

Something like:

Assignment.order(priority: ['best', 'good', 'bad'])

and this will return all activerecords first with 'best', then 'good', then 'bad'

I cannot seem to find anything like this. I do not need an array, it has to be activerecords.

like image 715
sonnyhe2002 Avatar asked May 12 '14 23:05

sonnyhe2002


1 Answers

In newer versions of Rails you will get an ActiveRecord::UnknownAttributeReference (Query method called with non-attribute argument(s) error if you pass raw SQL to .order().

You need to wrap your SQL query with Arel.sql(). You can also use ruby's Here Doucment syntax, to write multi line SQL statements, and squish to make it more readable in the console.

So the whole thing becomes:

Assignment.order(
  Arel.sql(<<-SQL.squish
    CASE
      WHEN priority = 'best' THEN '1'
      WHEN priority = 'good' THEN '2'
      WHEN priority = 'bad' THEN '3'
    END
  SQL
  )
)
like image 190
wnm Avatar answered Sep 17 '22 16:09

wnm