2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

レコードを更新したときのレコードの並びが、ローカル環境(sqlite)とHeroku(PostgreSQL)で異なる

Last updated at Posted at 2015-12-03

現象

データベースにレコードを追加・更新していった場合、
ローカル環境(sqlite)ではレコードがidの昇順になっているが、
Heroku(PostgreSQL)では順序が異なる。

ローカル環境(sqlite)
 id |         title          |         created_at         |         updated_at         
----+------------------------+----------------------------+----------------------------
  1 | hoge1                  | 2015-07-11 03:01:41.459369 | 2015-07-10 19:30:38.917108
  2 | hoge2                  | 2015-07-12 03:03:41.459369 | 2015-12-03 07:22:19.342057
  3 | hoge3                  | 2015-07-12 03:05:41.459369 | 2015-09-10 21:13:38.917108
  4 | hoge4                  | 2015-09-11 03:01:41.459369 | 2015-12-03 07:22:04.481084
Heroku(PostgreSQL)
 id |         title          |         created_at         |         updated_at         
----+------------------------+----------------------------+----------------------------
  1 | hoge1                  | 2015-07-11 03:01:41.459369 | 2015-07-10 19:30:38.917108
  3 | hoge3                  | 2015-07-12 03:05:41.459369 | 2015-09-10 21:13:38.917108
  4 | hoge4                  | 2015-09-11 03:01:41.459369 | 2015-12-03 07:22:04.481084
  2 | hoge2                  | 2015-07-12 03:03:41.459369 | 2015-12-03 07:22:19.342057

原因

PostgreSQLでは、レコードを追加または更新した順序で表示している。
(追加または更新が最新のものが下にくる)

対処法

きちんと決まった順序でレコードを取得したい場合には、ORDER BYを指定してやればよい。
たとえば、idの昇順で全件取得したい場合、

hoge_controller.rb
@hoges = Hoge.all.order("id ASC")
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?