Rails with Postgres data is returned out of order

2020-07-18 06:14发布

问题:

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

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

If I add an order clause like this:

Person.order("id").first

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

回答1:

this post answers your question:

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')

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