Take the 2-minute tour ×


    - book.prices.order(:currency_code).each do |price|

returns all a book's prices ordered alphabetically by currency code:

AUD 19.99 
GBP 9.99 
NZD 26.00 
USD 14.95

Now, how can I neatly get GBP to always appear at the top of the list, with the others sorting alphabetically, like this:

GBP 9.99 
AUD 19.99 
NZD 26.00 
USD 14.95

This answer shows the SQL solution, but I'm not sure about the Rails way.

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Since ordering is normally done on DB level, just use the SQL solution in rails:

- book.prices.order("`currency_code` = 'GBP' desc, currency_code").each do |price|

you can use sql snippets in Rails (ActiveRecord) query methods.
Depending on your DB you might have to choose the right SQL solutiuon, so probably

- book.prices.order("CASE WHEN currency_code = 'GBP' THEN 1 ELSE 2 END, currency_code").each do |price|

works in your case.
You can check the resulting sql in rails console:


and check, whether it works in you DB.

An other way is of cause to add an extra column for sorting, this way you can even position commonwelth currencies in front of others etc.

share|improve this answer
Thanks for that -- now that's parsing I can see that the SQL solution doesn't actually work. I'm just getting a list ordered alphabetically, with no GBP at the top. –  snowangel Jul 14 '13 at 9:16
try the other SQL solutions, they depend on DB brand. I updated my answer. –  Martin M Jul 14 '13 at 9:34
Brilliant -- take out the dodgy 'city' and the second answer works beautifully. Thanks. –  snowangel Jul 14 '13 at 9:38
city removed,(was a copy&paste left over, sorry) –  Martin M Jul 14 '13 at 9:40
add comment

Your Answer


