Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 当我对计数器缓存进行排序时,它首先返回nil对象?_Ruby On Rails_Counter Cache - Fatal编程技术网

Ruby on rails 当我对计数器缓存进行排序时,它首先返回nil对象?

Ruby on rails 当我对计数器缓存进行排序时,它首先返回nil对象?,ruby-on-rails,counter-cache,Ruby On Rails,Counter Cache,我在我的项目模型上拥有\u计数计数器\u缓存。当我这样做的时候 Items.order("owns_cache DESC") ,它返回在其他结果之前为零的对象。如果我这样做 "owns_cache ASC" ,这是正确的 我应该怎么做?空值的排序方式取决于基础数据库 对于PostgreSQL,您可以执行以下操作: Items.order("owns_cache DESC NULLS LAST") 对于MySQL和SQLite: Items.order("COALESCE(owns_cach

我在我的项目模型上拥有\u计数计数器\u缓存。当我这样做的时候

Items.order("owns_cache DESC")
,它返回在其他结果之前为零的对象。如果我这样做

"owns_cache ASC"
,这是正确的


我应该怎么做?

空值的排序方式取决于基础数据库

对于PostgreSQL,您可以执行以下操作:

Items.order("owns_cache DESC NULLS LAST")
对于MySQL和SQLite:

Items.order("COALESCE(owns_cache, 0) DESC")
我认为MySQL在DESC排序的底部对null进行排序,因此您可能不需要任何特殊的东西。这种合并方法也适用于PostgreSQL,因此这将是一个可移植的解决方案,可以在任何地方为您提供一致的结果

如果您希望在ASC排序的底部为空,则应将
0
替换为大于最大
owns\u缓存数的值