问题描述
在我的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 =零
和一些地方 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?
推荐答案
添加阵列将共同preserve命令:
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的:订单与空值最后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!