LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby on Rails】選択ボックスをモデルの情報を元に生成する方法

Posted at

前提条件

  • Ruby 3.1.0
  • Rails 7.0.4

やりたいこと

選択ボックスをvegetableテーブルの情報を元に生成したい。

vegetableテーブル

id name
1 たまねぎ
2 じゃがいも
3 にんじん

方法

collection_selectメソッドを使う

vegetable_controller.rb
def new
  @veges = Vegetable.all
end
new.html.erb
<%= f.collection_select(:name, @veges, :id, :name) %>

第一引数:フォームの対象モデルの中の該当する属性名を設定する。
第二引数:選択肢の情報として提供する。
第三引数:フォームのvalueを設定する。
第四引数:optionタグ内のテキストを設定する。

結果

選択ボックスをvegetableテーブルの情報を元に生成することができた。
スクリーンショット 2023-02-17 13.47.21.png

参考

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