diasks2
diasks2

Reputation: 2142

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>

Upvotes: 1

Views: 1510

Answers (2)

Soundar Rathinasamy
Soundar Rathinasamy

Reputation: 6728

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' %>

Upvotes: 8

flooooo
flooooo

Reputation: 709

Try setting a value for selected.

Refer to: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select

Edit: Can't test it now but I'm pretty sure select will take the array of options by itself. So you shouldn't need options_for_select here - then selectshould set the selected option.. Try this and refer to: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

Upvotes: 0

Related Questions