ActiveRecord的查找所有不是由ID排序? [英] ActiveRecord Find All not sorting by ID?
问题描述
我在Heroku的部署,我似乎无法复制本地有一个奇怪的问题。基本上,当我发现所有在一个特定的模式,而不是通过ID进行排序,似乎他们没有秩序可言回报。
I've got a strange issue on a Heroku deployment that I can't seem to duplicate locally. Basically when I find all on a specific model instead of sorting by ID it seems to return them in no order at all.
通常情况下,记录出来,像这样:
Typically the records come out like so:
>> Model.all
=> [<model id: 2>,<model id: 1>,<model id: 3>,<model id: 4>,<model id: 5>]
...等等。
... and so on.
如果我明确地调用 Model.order(ID ASC)
返回模型预期。
If I explicitly call Model.order("id ASC")
it returns the models as expected.
怎么办?为什么会找到所有不返回的对象按降序ID顺序?
What gives? Why would find all not return the objects in descending ID order?
推荐答案
排序方式ID是的没有的默认保证的,因为它是由数据库如何无序查询被下令(通常是未指定)。你可以把它总是在顶部定义默认范围订购你的模型像这样:
Ordering by ID is not guaranteed by default, since it’s up to the database how a non-ordered query gets ordered (typically it’s unspecified). You can make it always be ordered by defining a default scope at the top of your model like so:
default_scope order('id ASC')
然后调用 Model.all
将相当于调用 Model.order('身份证ASC')
。
这篇关于ActiveRecord的查找所有不是由ID排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!