Reputation: 3462
This:
- 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.
Upvotes: 8
Views: 2658
Reputation: 8668
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
:
book.prices.order("CASE WHEN currency_code = 'GBP' THEN 1 ELSE 2 END, currency_code").to_sql
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.
Upvotes: 14