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 1 year has passed since last update.

【Ruby】pluckメソッド

Posted at

引数に指定したカラムの値を配列で返してくれるメソッド

pluck(:hogehoge)
User.pluck(:firstname)

User.all.map(&:firstname) # 上記と同じ

# =>  ["太郎", "二郎", "新一", "平次"]

結果は同じだが、発行されるSQLが異なる。
pluckメソッドは、SQLの段階から取得するカラムのデータを絞り込んでいる
mapメソッドは、全てのデータを取得した後そのデータから特定のカラムのデータを取得している

User.pluck(:firstname)
SELECT `users`.`firstname` FROM `users`

User.all.map(&:firstname)
SELECT `users`.* FROM `users`

引数2つ指定もできる。

Employee.pluck(:firstname, :lastname)

# => [["太郎", "山田"], ["二郎", "安倍"], ["新一", "工藤"], ["平次", "服部"]]

##参考

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?