Rails:最后用空值排序 [英] Rails: Order with nulls last

查看:36
本文介绍了Rails:最后用空值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Rails 应用中,我遇到过几次问题,我想知道其他人是如何解决的:

In my Rails app I've run into an issue a couple times that I'd like to know how other people solve:

我有某些记录的值是可选的,因此对于该列,有些记录具有值,而有些记录为空.

I have certain records where a value is optional, so some records have a value and some are null for that column.

如果我在某些数据库上按该列排序,则空值首先排序,而在某些数据库中,空值排序最后.

If I order by that column on some databases the nulls sort first and on some databases the nulls sort last.

例如,我有一些照片可能属于也可能不属于某个收藏集,即有一些照片在 collection_id=nil 和一些在 collection_id=1 等位置.

For instance, I have Photos which may or may not belong to a Collection, ie there are some Photos where collection_id=nil and some where collection_id=1 etc.

如果我执行 Photo.order('collection_id desc) 那么在 SQLite 上我最后得到空值,但在 PostgreSQL 上我首先得到空值.

If I do Photo.order('collection_id desc) then on SQLite I get the nulls last but on PostgreSQL I get the nulls first.

是否有一种很好的标准 Rails 方法来处理这个问题并在任何数据库中获得一致的性能?

Is there a nice, standard Rails way to handle this and get consistent performance across any database?

推荐答案

将数组相加将保持顺序:

Adding arrays together will preserve order:

@nonull = Photo.where("collection_id is not null").order("collection_id desc")
@yesnull = Photo.where("collection_id is null")
@wanted = @nonull+@yesnull

http://www.ruby-doc.org/core/classes/Array.html#M000271

这篇关于Rails:最后用空值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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