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.
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
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With