按字母顺序排列,但在顶部有一个值 [英] Order alphabetically, but with one value at the top

查看:65
本文介绍了按字母顺序排列,但在顶部有一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个:

    - 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

这个答案显示了 SQL解决方案,但我不确定 Rails 的方式.

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

推荐答案

由于排序通常是在 DB 级别完成的,因此只需使用 rails 中的 SQL 解决方案:

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|

您可以在 Rails (ActiveRecord) 查询方法中使用 sql 片段.
根据您的数据库,您可能必须选择正确的 SQL 解决方案,所以可能

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|

适用于您的情况.
您可以在 rails 控制台 中检查生成的 sql:

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.

这篇关于按字母顺序排列,但在顶部有一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆