activerecord模型的默认排序顺序?

时间:2013-09-04 08:40:27

标签: ruby-on-rails activerecord

如果我没有在模型(帐户)中设置default_scope,只需调用Account.first,将返回哪个项目?

这是一个例子: 帐户表有5条记录,Account.all返回:

  Account.all.map{ |x| {id: x.id, name: x.name, created_at: x.created_at, updated_at:x.updated_at}}
  Account Load (0.5ms)  SELECT "accounts".* FROM "accounts"
=> [{:id=>2,
  :name=>"Hessel, Kirlin and Gulgowski",
  :created_at=>Wed, 04 Sep 2013 00:44:33 EDT -04:00,
  :updated_at=>Wed, 04 Sep 2013 00:44:33 EDT -04:00},
 {:id=>3,
  :name=>"Hessel, Kirlin and Gulgowski",
  :created_at=>Wed, 04 Sep 2013 00:44:34 EDT -04:00,
  :updated_at=>Wed, 04 Sep 2013 00:44:34 EDT -04:00},
 {:id=>4,
  :name=>"Hessel, Kirlin and Gulgowski",
  :created_at=>Wed, 04 Sep 2013 00:44:34 EDT -04:00,
  :updated_at=>Wed, 04 Sep 2013 00:44:34 EDT -04:00},
 {:id=>5,
  :name=>"Hessel, Kirlin and Gulgowski",
  :created_at=>Wed, 04 Sep 2013 00:44:35 EDT -04:00,
  :updated_at=>Wed, 04 Sep 2013 00:44:35 EDT -04:00},
 {:id=>1,
  :name=>"EIS",
  :created_at=>Wed, 04 Sep 2013 00:44:31 EDT -04:00,
  :updated_at=>Wed, 04 Sep 2013 00:44:32 EDT -04:00}]

Account.first返回id为2的记录,我没有在模型中设置default_scope,为什么id为2而不是id为1?

谢谢!

更新:我喜欢这个答案(https://stackoverflow.com/a/4986620/655621

1 个答案:

答案 0 :(得分:0)

我的理解是,在没有订单的情况下,将使用id的默认订单,但至少在3.2.13中似乎不是这种情况

2.0.0p247 :001 > Book.first
  Book Load (60.0ms)  SELECT "books".* FROM "books" LIMIT 1

所以最近的版本可能会有代码更改。你用的是哪个版本?