9
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

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

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"

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
9
Help us understand the problem. What are the problem?