Qiita Conference 2025

鹿野壮 (@tonkotsuboy_com)

アウトプットは最強の自己投資 〜発信が人生とキャリアを変えた話〜

11
9

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.

ActiveRecord findメソッドにidを配列で渡した結果はRelationではない

Last updated at Posted at 2015-01-12

Rails4でfindにidの配列を渡すと、

profiles = Profile.find [1,2,3,4,5]
  # =>  SELECT "profiles".* FROM "profiles"  WHERE "profiles"."id" IN (1, 2, 3, 4, 5)
profiles.class
  # => Array

となり、結果はただの配列でActiveRecordの恩恵を受けられません。
素直にwhereで取得したほうがいいです。SQLも同じなので特に問題なさそうです。

profiles = Profile.where id: [1,2,3,4,5]
  # =>  SELECT "profiles".* FROM "profiles"  WHERE "profiles"."id" IN (1, 2, 3, 4, 5)
profiles.class
  # => Profile::ActiveRecord_Relation

Environment

pry(main)> Rails.version
=> "4.1.6"
11
9
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?