带有Postgres数据的Rails乱序返回 [英] Rails with Postgres data is returned out of order

查看:65
本文介绍了带有Postgres数据的Rails乱序返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚将我的应用程序从MySQL过渡到了Postgres.以前,对.all的请求按id顺序返回了所有行.在Postgres上,这些行是按无序返回的.同样,

I've just transitioned my app from MySQL to Postgres. Previously, a request for .all returned all the rows in id order. On Postgres the rows are returned out of order. Likewise,

Person.first

用于返回ID为1的记录,现在有时返回另一条记录.

used to return the record with id 1, now it sometimes returns another record.

如果我添加这样的order子句:

If I add an order clause like this:

Person.order("id").first

查询成功并返回第一行.这是预期的行为吗?

The query succeeds and returns the first row. Is this expected behaviour?

推荐答案

此帖子回答您的问题:

我不认为默认情况下按ID排序是保证的,因为我认为这取决于数据库如何返回无序查询.您可以通过在模型顶部定义默认范围来进行排序,如下所示:

I don't think ordering by ID is guaranteed by default, since I believe it's up to the database how a non-ordered query gets returned. You can make it be ordered so by defining a default scope at the top of your model like so:

default_scope order('id ASC')

然后调用Model.all将等同于调用Model.order('id ASC').

Then calling Model.all will be equivalent to calling Model.order('id ASC').

这篇关于带有Postgres数据的Rails乱序返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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