Search code examples
ruby-on-rails-4grouped-collection-select

grouped_options_for_select in rails 4


I done grouped_options_for_select. I want a prompt. If there no options to select under the group, there should not any space. I try with the following code.
controller:

 @grouped_options = @subjects.inject({}) do |options, product|
     (options[product.subject_name] ||= []) << [product.module_name, product.subject_module_id] 
     options
 end  

view:

<div id="subject_module_drp_div">
    <%= f.select :subject_module_id, grouped_options_for_select(@grouped_options), 
                    {:class=>"form-control select_modules",:style=>"width:100%;"} %>
</div>  

my options for select like,

Grammar:
Tense
Voice

Science:

Maths:
Algebra
Trignomentry

Here Science has no option to select. So maths comes immediate next to science. There is no space between science and maths. Is there any option to do this in the grouped_options_for_select. And how to give prompt value and get already selected options.
Smile & Thanks.


Solution

  • I try more search with this issue and get solution. Sorry for the question here before thorough check.And my answer is,
    Controller:

    (options[product.subject_name] ||= []) << if product.module_name != nil then [product.module_name, product.subject_module_id] else ["Nil", :disabled => true] end   
    

    View:

    <%= f.select :subject_module_id, grouped_options_for_select(@grouped_options, selected: @faculty_profile.subject_module_id),
            {:prompt => 'Select Module'}, {:class=>"form-control select_modules",:style=>"width:100%;"} %>  
    

    This works well for me. Thanks.