Search code examples
ruby-on-railsruby-on-rails-3formsdrop-down-menuform-helpers

Rails: nested form binded to an object – problems with select box


I have a nested form model in my Rails app. When I go to edit an object in the model, all of my fields (text_area, check_box, etc.) are populated with data from the database except for the select box. How can I get my select box to also populate when I am using the form to edit existing data from the model?

<%= form_for @test do |f| %>

  <%= f.fields_for :questions do |builder| %>
    <%= render 'question_fields', f: builder %>
  <% end %>

<% end %>

_question_fields.html.erb

<fieldset>

  <%= f.text_area :question_text %>

  <%= f.select :correct_answer, options_for_select([['A', 1], ['B', 2], ['C', 3], ['D', 4], ['E', 5]]), :prompt => 'Choose the correct answer' %>

  <%= f.check_box :question_check %>

</fieldset>

Solution

  • You need to send the selected parameter in options_for_select function call.

    <%= f.select :correct_answer, options_for_select([['A', 1], ['B', 2], ['C', 3], ['D', 4], ['E', 5]], :selected => f.object.correct_answer), :prompt => 'Choose the correct answer' %>