1
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.

mapの使い方

Posted at

今回はmapの使い方を紹介します。

#使い方

基本的なフォーム


配列変数 = ["a", "b", "c"]  
配列変数.map {|変数名| 具体的な処理 }

categories = ["a", "b", "c"] # 配列
categories.map {|category| [category.name, category.id] }  # 配列の要素にid,nameを付与してひとつずつ出す

実際に使うときはselectで使うことが多いです。

application_controller.rb
def set_category
  @categories = Category.all
end

= form.select :category_id, @categories.map{ |category| [category.name, category.id] }, {prompt:"選択してください"}

#完成図

Image from Gyazo
Image from Gyazo

以上

1
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
1
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?