26
20

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.

任意のカラムの配列を取得する pluckメソッド

Posted at

##指定したカラムの配列を取得したい場合
 
pluckメソッド
引数にカラム名を指定すると、そのカラムの値が配列で返してくれる 

user.pluck(:name)
#=> ["satoshi", "kei", "yumi"]

またRails4からは、複数のカラムの指定もできる

user.pluck(:id, :name)
#=> [[1, "satoshi"], [2, "kei"], [3, "yumi"]]

 
ActiveRecordのオブジェクトの生成コストは大きい。
pluckメソッドはActiveRecordオブジェクトを生成せず要素を返すため動作が早い。
DBから値を取ってくる時はmapよりpluckの方がおすすめ。

##参考サイト
Railsドキュメント

26
20
1

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
26
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?