[英]Rails 4 - Order by the presence of an attribute
Using Rails 4. Psql DB. 使用Rails 4. Psql DB。
I have a model Article
with an attribute amazon_title
. 我有一个带有属性
amazon_title
的模型Article
。 I am having trouble understanding how I can order my articles so articles with the amazon_title
present are first, and ones without are second. 我无法理解如何订购我的文章所以使用
amazon_title
存在的文章是第一个,没有的文章是第二个。
I've tried ordering them like this with no success: 我试过像这样订购它们没有成功:
Article.all.order(amazon_title: :desc)
The above orders it alphabetically, showing blank first, present second, and nil third. 以上按字母顺序排序,显示空白,第二,第三,第三。
I feel like this is very simple, but for some reason I cannot find the answer. 我觉得这很简单,但由于某种原因我找不到答案。 Thanks!
谢谢!
For PostgreSQL (the order will be true
, false
, nil
): 对于PostgreSQL(顺序为
true
, false
, nil
):
Article.order('amazon_title DESC NULLS LAST')
Another option (database agnostic): 另一种选择(数据库不可知):
Article.order('(CASE WHEN amazon_title THEN 1 WHEN amazon_title IS NULL THEN 2 ELSE 3 END) ASC')
In PostgreSQL you can pass NULLS FIRST
OR NULLS LAST
depending on your requirement. 在PostgreSQL中,您可以根据您的要求通过
NULLS FIRST
或NULLS LAST
。 That's why I asked you about your DB. 这就是我问你关于你的数据库的原因。
Article.order('amazon_title DESC NULLS FIRST')
the above will list the NULLS first and 以上将首先列出NULLS和
Article.order('amazon_title DESC NULLS LAST')
and this one will list the NULL records last. 这个将最后列出NULL记录。
Hope that helps! 希望有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.