Andy Harvey
Andy Harvey

Reputation: 12663

How to define a select field in a nested form?

What is the correct way to include a select field within a nested form in Rails 3.2?

I currently have

//IN THE PARENT FORM

<%= f.fields_for :crayons  do |crayon| %>
   <%= render 'caryon_fields', :f=>crayon %>
<% end %>

//IN THE PARTIAL

<div class="nested-fields">
   <%= select (:crayon, :color, [['Red',1],['Blue',2],['Yellow',3],['Green',4]] ) %>
</div>

This is not saving the selected value to the database. I assume this is because the builder is not being passed.

How should I define a select field with hardcoded options in a nested field? Do I need to change tag, i.e. select_tag or collection_select. I'm still unsure of the differences between all these. If anyone can point me towards a clear description it would be much appreciated.

Thanks!

Upvotes: 0

Views: 1865

Answers (1)

shingara
shingara

Reputation: 46914

You need associate to your form in your partial like that :

<div class="nested-fields">
   <%= f.select (:crayon, :color, [['Red',1],['Blue',2],['Yellow',3],['Green',4]] ) %>
</div>

Whitout partial it's :

<%= f.fields_for :crayons  do |crayon| %>
  <div class="nested-fields">
   <%= crayon.select (:crayon, :color, [['Red',1],['Blue',2],['Yellow',3],['Green',4]] ) %>
  </div>
<% end %>

Upvotes: 2

Related Questions