[Ruby]pluckメソッド
書き方
@post = Post.pluck(:id,:title)
例
pry: @post
=> [[1,abc], [2,cde], [3,efg], ...]
下記ようにPostモデル内のtitleカラムを一覧表示することができる。
Post.pluck(:title)
=> ["Tote",
"Bag",
"Baseball Jersey",
"Jr.Spaghetti",
"Ringer T-Shirt",
"Ruby Baseball Jersey",
"Apache Baseball Jersey",
"Mug",
"Stein"]
また、このように第二引数を設定することも可能。
Post.pluck(:id,:title)
=> [[1, "Tote"],
[2, "Bag"],
[3, "Baseball Jersey"],
[4, "Jr. Spaghetti"],
[5, "Ringer T-Shirt"],
[6, "Ruby Baseball Jersey"],
[7, "Apache Baseball Jersey"],
[8, "Mug"],
[9, "Stein"]]
ちなみに下記は同じ意味のコード
Post.select(:id, :title).map { |c| [c.id, c.title] }
シンプルに出来る
Author And Source
この問題について([Ruby]pluckメソッド), 我々は、より多くの情報をここで見つけました https://qiita.com/___fff_/items/438c54ad530dc14cefb9著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .