LoginSignup
4
4

More than 5 years have passed since last update.

Rails5 で `find(ids)` の戻り値が、渡した id の順番で返ってくるようになった

Posted at

そのまんまの話。

rails4 と rails5 で同じ DB に接続しています。

rails4
> DailyReport.find(10, 4, 2, 7).map(&:id)
  DailyReport Load (0.4ms)  SELECT "daily_reports".* FROM "daily_reports" WHERE "daily_reports"."id" IN (10, 4, 2, 7)
=> [2, 4, 7, 10]
rails5
> DailyReport.find(10, 4, 2, 7).map(&:id)
  DailyReport Load (0.5ms)  SELECT "daily_reports".* FROM "daily_reports" WHERE "daily_reports"."id" IN (10, 4, 2, 7)
=> [10, 4, 2, 7]

地味に便利かもしれない。

ちなみに、引数に重複があっても戻り値は重複しないので、もし重複があると引数と戻り値の個数が合わなくなります。
これは rails4 から変わってません。
重複させて find するとかあまりないとは思うけれども。

rails4
> DailyReport.find(10, 4, 2, 7, 2, 11).map(&:id)
  DailyReport Load (0.6ms)  SELECT "daily_reports".* FROM "daily_reports" WHERE "daily_reports"."id" IN (10, 4, 2, 7, 11)
=> [2, 4, 7, 10, 11]
rails5
> DailyReport.find(10, 4, 2, 7, 2, 11).map(&:id)
  DailyReport Load (0.4ms)  SELECT "daily_reports".* FROM "daily_reports" WHERE "daily_reports"."id" IN (10, 4, 2, 7, 11)
=> [10, 4, 2, 7, 11]

.find なので、存在しない id が含まれていると ActiveRecord::RecordNotFound 例外になるのも変わりません。
(ここが変わると困ってしまいますが)

rails4
> DailyReport.find(1, 999999)
  DailyReport Load (0.2ms)  SELECT "daily_reports".* FROM "daily_reports" WHERE "daily_reports"."id" IN (1, 999999)
ActiveRecord::RecordNotFound: Couldn't find all DailyReports with 'id': (1, 999999) (found 1 results, but was looking for 2)
rails5
irb(main):001:0> DailyReport.find(1, 999999)
  DailyReport Load (0.1ms)  SELECT "daily_reports".* FROM "daily_reports" WHERE "daily_reports"."id" IN (1, 999999)
ActiveRecord::RecordNotFound: Couldn't find all DailyReports with 'id': (1, 999999) (found 1 results, but was looking for 2)
4
4
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
4
4