1

I am trying to do a "ORDER BY FIELD" in active record. I know that i can do it with MySQL but i am trying to keep my app agnostic and follow best practice. my production db is PostgreSQL

the MySQL looks like

SELECT id, name
FROM mytable
WHERE name IN ('B', 'A', 'D', 'E', 'C')
ORDER BY FIELD(name, 'B', 'A', 'D', 'E', 'C')
MZaragoza
  • 10,108
  • 9
  • 71
  • 116
  • Asked and answered I think : http://stackoverflow.com/questions/1309624/simulating-mysqls-order-by-field-in-postgresql – xQbert Nov 11 '13 at 19:30
  • Thanks that helps but i don't want to Simulating MySQL's in PG but i want to be able to do it with active record. Thanks for the help – MZaragoza Nov 11 '13 at 19:33

2 Answers2

2

I was trying to make it happen and this is what i came with. I still think that this can be a bit cleaner

Model.select(:id).select(:name).order("status = 'B' DESC, status = 'A' DESC, status = 'D' DESC, status = 'E' DESC, status = 'C' DESC")
MZaragoza
  • 10,108
  • 9
  • 71
  • 116
1

One agnostic option is to move your status values into another model and have an extra attribute for the sort order.

David Aldridge
  • 51,479
  • 8
  • 68
  • 96