How to use :selected with grouped_collection_select

后端 未结 3 1216
逝去的感伤
逝去的感伤 2021-01-13 04:01

Is it possible to somehow use the :selected option that you\'d use on a normal select view helper with the grouped_collection_select function? I\'d like to set the value th

3条回答
  •  感情败类
    2021-01-13 04:07

    I just ran across the same problem and solved it using the option_groups_from_collection_for_select helper and the select helper documented at: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html.

    The first step is to create the grouped options. Taking your example, it should look like:

    <% options = option_groups_from_collection_for_select(Trade.order(:name).all,
       :subscription_plans, :name, :id, :display_name, 5) %>
    

    Then I created the select object like:

    <%= select('user[subscription_attributes]', :subscription_plan_id, options, 
      include_blank: true) %>
    

    You could write it all out in one line, I just broke out the options into a separate variable to illustrate the two different methods.

提交回复
热议问题