LoginSignup
1
1

More than 1 year has passed since last update.

railsのform_withにおけるselectメソッドの初期値設定方法

Last updated at Posted at 2022-05-31

概要

form_withにおけるselectメソッドの初期値の設定方法が地味に迷ったのでまとめます。

初期値設定方法について

初期値設定方法は大きく2つあります。

options_for_selectを使う方法

# bが選択される
= f.select :hoge, options_for_select(["a","b","c"], selected: "b")

options_for_select を使わない方法

# bが選択される
= f.select :hoge, ["a","b","c"], { selected: "b" }

注意点

失敗例

これだと失敗する。

# aが選択される
= f.select :hoge, [["a", 1],["b", 2],["c", 3]], { selected: "b" }

解決策

選択肢が二次元配列で渡されている場合(1つの選択肢が複数の要素を持っている場合)、最初の要素がページ上に出力され、最後の要素がoptionタグのvalueに設定されるため、最後の要素で指定する必要がある。(2~n-1番目(n >= 3)の要素はどこにも使われない)

# bが選択される
= f.select :hoge, [["a", 1],["b", 2],["c", 3]], { selected: 2 }
# bが選択される
= f.select :hoge, [["a", 2, 1],["b", 3, 2],["c", 1, 3]], { selected: 2 }

おまけ

クラスを付与する場合は以下のようになる

# bが選択される
= f.select :hoge, [["a", 1],["b", 2],["c", 3]], { selected: 2 }, { class: ['hoge'] }
1
1
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
1