LoginSignup
0
0

More than 1 year has passed since last update.

[Rails]特定のカラムの値を取得(pluck)

Posted at

Pluckメソッド

指定したカラムの値を配列で返してくれます。

モデル名.pluck(取得したいカラム名)

【例】usersテーブル

id name bounty
1 ルフィ 30億
2 バギー 31億8900万
3 ティーチ 39億9600万
4 シャンクス 40億4890万

上記のようなusersテーブルからnameカラムの値だけ取得したい場合、pluckメソッドを用いると便利です。Userモデルを指定し、引数にカラム名nameを渡します。

User.pluck(:name)

=> ["ルフィ", "バギー", "ティーチ", "シャンクス"] # 返り値

また、引数に複数のカラムを指定することもできます。

User.pluck(:name, :bounty)
=> [["ルフィ","30億"], ["バギー","31億8900万"], ["ティーチ","39億9600万"], ["シャンクス","40億4890万"]] # 返り値

複数カラムを指定した時の返り値は、二次元配列になっています.

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