How to use: selected with grouped_collection_select

Is there any way to use the: selected parameter, which you would use in a regular select view helper with the grouped_collection_select function? I would like to set a value to be preselected in my list. I tried the transition: selected as an option with no luck!

Here are some snippts of my test code:

grouped_collection_select 'user[subscription_attributes]', :subscription_plan_id, Trade.order(:name).all, :subscription_plans, :name, :id, :display_name, { :include_blank => true, :selected => 5 }

grouped_collection_select 'user[subscription_attributes]', :subscription_plan_id, Trade.order(:name).all, :subscription_plans, :name, :id, :display_name, :include_blank => true, :selected => 5 

None of the versions work. Selected not selected. I use this to set the value for a nested model. I use railscasts dynamic selection methods: http://railscasts.com/episodes/88-dynamic-select-menus-revised

I could not get formtastic to play well with the group, so I had to do it manually, but I do not save this value when the user fails. I would like to keep this set when they fix validation errors.

+5
source share
3 answers

I just encountered the same problem and solved it using option_groups_from_collection_for_select helperand selectassistant, registered at the address: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html .

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

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

Then I created a select object, for example:

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

, , .

+9

, , API grouped_collection_select : ' , .'

, : Rails . subscription_plan_id 5, .

, , after_initialize .

+1

include_blank,

<%= grouped_collection_select :id, model.all, options = {:include_blank => 'Selecione'}%>
0

All Articles