0
0

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 3 years have passed since last update.

pluckメソッドとは

Posted at

今回、pluckメソッドについて学習したため、アウトプットいたします。

pluckメソッドとは?
その使い方とは?

について記述いたします。

pluckメソッドとは?

pluckメソッドとはこう書かれています。
「引数に指定したカラムの値を配列で返すメソッド。」

同様の効果のあるメソッドとしてmapメソッドが上げられますが、返り値を配列として取得する場合は、pluckメソッドを使った方がシンプルで楽です。

では実際に使ってみましょう。

使い方

usersテーブルのnameカラムに"田中", "吉田", "鈴木", "高橋"の4人が入っていたとする。
そこで、userテーブルのnameカラムだけ取得したい場合、pluckメソッドは力を発揮する

User.pluck(:name)
# すると以下のような処理がされる
SELECT `users`.`name` FROM `users`
=> ["田中", "吉田", "鈴木", "高橋"] # 返り値

このようにテーブルやデータベースに登録された情報を配列としてまとめて取得したい場合にとても便利です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?