ActiveRecord Find All 不按 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>]
...等等.
如果我显式调用 Model.order("id ASC")
它会按预期返回模型.
If I explicitly call Model.order("id ASC")
it returns the models as expected.
什么给?为什么 find all 不返回按 ID 降序排列的对象?
What gives? Why would find all not return the objects in descending ID order?
推荐答案
默认情况下不保证按 ID 排序.无序查询如何排序取决于数据库(通常是未指定的).如果您希望对结果进行排序,则需要使用 order
,正如你所做的:
Ordering by ID is not guaranteed by default. It’s up to the database how a non-ordered query gets ordered (typically it’s unspecified). If you want your results to be ordered, you need to specify an explicit order with order
, as you’ve done:
Model.order(id: :asc)
另请注意,仅当您需要确定性顺序时,才应按 id
进行排序.如果您想按时间排序,请使用 created_at
或 updated_at
(不能保证 id
是按时间顺序排列的).如果您希望始终对所有查询进行排序,则可以使用 default_scope
,但通常应避免使用它.
Note also that ordering by id
should only be done if you want a deterministic order. If you want to order by time, use created_at
or updated_at
(nothing guarantees that id
s are chronologically ordered). If you want all queries to always be ordered, you could use default_scope
, but generally its use should be avoided.
这篇关于ActiveRecord Find All 不按 ID 排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!