LoginSignup
21
21

More than 3 years have passed since last update.

ActiveRecordから任意のカラムの配列を取得する

Last updated at Posted at 2020-04-25

はじめに

Rails を使っている時に、where で検索した複数レコードの内、任意のカラムの配列を取得したい時がありました。

pluckメソッドを使う

ActiveRecord のメソッドを色々見てると pluck というメソッドが有りました、日本語でむしるという意味らしいです。

引数にカラム名を指定して使います。

users_controller.rb
 male_names = User.where(gender: "male").pluck(:name)

以下のように配列が取得できます。

  ["太郎", "次郎"]

ちなみに複数のカラムの指定もできます。

users_controller.rb
 # id と name のみを取り出したいケース
 male_names = User.where(gender: "male").pluck(:id, :name)

以下のように取得できます。


  [[1,"太郎"], [3,"次郎"]]
21
21
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
21
21