Search code examples
ruby-on-railsrubyruby-on-rails-3models

Populate Dropdown based on another dropdown in ruby on rails


I have a two different fields in my form like below.

 <div class="field">
      <%= f.label :Master_Survey %><br/>
      <%= f.select :master_survey, Condition::MasterSurvey.all.map{|e| [e.Master_Survey_Code]}, { :prompt => 'Please Select' } %>
    </div>


    <div class="field">
      <%= f.label :Element_Code %><br/>
      <%= f.select :Element_Code, Condition::Element.all.map{|e| [e.Element, e.Element_Code]}, { :prompt => 'Please Select' } %>
    </div>

I want the second field should disabled unless the first got selected. And The Second field Element code should change the value depend upon the First field Master Survey selected. I have a Master Survey Code in the Elements Table.


Solution

  • If these two models are related via has_many/belongs_to or something similar, the best bet is going to use the grouped_collection_select method for your drop downs. This will organize your drop down into a tabbed-list (using optgroup), but then doing some jQuery magic to make the 2 drop down selections dynamic and chained!

    Ryan Bates has a RailsCast that explains in great detail exactly how to do this. If you don't have a pro-subscription to RailsCasts, I highly recommend getting one so you can easily find out how to do things like this :)

    Hope this points you in the right direction!