質問

[1] pry(main)> User.first
  User Load (0.4ms)  SELECT "users".* FROM "users" LIMIT 1
=> #<User id: 3, email: "chasity@kiehn.net", encrypted_password: "$2a$10$lqsgKvQuz9iSIu/..FMRJu76H9KNhfVz5x9DmxphC0TK...", reset_password_token: ... >
[2] pry(main)> User.find(1)
  User Load (12.8ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
=> #<User id: 1, email: "admin@example.com", encrypted_password: "$2a$10$pGDcv0/EgiDk4KcZN9pli.evx5Ni1qOoujQD15HgWH8Y...", reset_password_token: ... >
[3] pry(main)> Product.first
  Product Load (0.6ms)  SELECT "products".* FROM "products" LIMIT 1
=> #<Product id: 1, name: "Ruby on Rails Jr. Spaghetti", created_at: "2012-01-25 10:13:26", updated_at: "2012-01-25 10:13:26", properties: ...>

This is happening in the console and during runtime and only for the User model. What could cause such behaviour?

役に立ちましたか?

解決

You haven't specified an order - the database is free to order the results in any way it wants. It could be primary key order, it could be how things are laid out on disc but without an order clause there are no guarantees.

If you want the first record in a specific order, then make sure you ask for it

他のヒント

User.first is the same as User.all.first, there is no specified order, so the DB returns the list of element in any order. If you want to get the User with smallest id, use User.order("id").first.

If your request returns several elements and you want to pick any of them, you may want to use first without specified order.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top