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
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?