LoginSignup
6
2

More than 3 years have passed since last update.

rails の grouped_options_for_select で selected を指定する方法

Posted at

grouped_options_for_select に selected を指定したい

grouped_options_for_selectrailsドキュメントにはoptions_for_selectrails ドキュメントにある

<%= select_tag 'page[name]', options_for_select({"Railsの基礎" => "rails_base", "Rubyの基礎" => "ruby_base"}, :selected => "ruby_base") %>
# <select id="page_name" name="page[name]"><option value="rails_base">Railsの基礎</option> 
# <option value="ruby_base">Rubyの基礎</option></select>

のような option に selected を指定するオプションはないようだ。
さてどうしたものか。。。
railsAPI を読んでみると...

ふむふむ、メソッドの引数に selected_key なるものを option の value を設定することでいけそうだ!

<%= select_tag 'page[name]', grouped_options_for_select([["基礎", [["Railsの基礎", "rails_base"], ["Rubyの基礎", "ruby_base"]]]], 'ruby_base') %>
# <select id="page_name" name="page[name]"><optgroup label="基礎"><option value="rails_base">Railsの基礎</option> 
# <option value="ruby_base">Rubyの基礎</option></optgroup></select>

これで 「Rubyの基礎」が selected の状態になる!

できそうだなと思ったら粘り強く調べるべし

実のところ僕自身は rails ドキュメントに記載されていなかった時点でできないものだと思い諦めていたところ, 先輩エンジニアの方が協力してくれて見つけることができた。 options_for_select では普通に指定できるわけだし grouped_options_for_select だからできないというのは確かに違和感があった。次からは rails の素晴らしい機能を信じて深く探してみよう。

6
2
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
6
2