Skip to content

Instantly share code, notes, and snippets.

@clm-a
Created March 16, 2011 09:44
Show Gist options
  • Save clm-a/872240 to your computer and use it in GitHub Desktop.
Save clm-a/872240 to your computer and use it in GitHub Desktop.
Howto : work with index in Rails 3's fields_for
<%= form_for parent do |parent_form_builder| %>
<%= parent_form_builder.text_field :name %>
<% parent.children.each_with_index do |child, index| %>
<% parent_form_builder.fields_for :children, child do |child_form_builder| %>
<%= child_form_builder.select :age, (0..99).to_a %>
<%# generates "parent[:children_attributes][index][age]" as name for the input %>
<% end %>
<% end %>
<%= f.submit %>
<% end %>
@danam
Copy link

danam commented Mar 6, 2012

Wanting to put all the response text fields into a tab system (from foundation). What is the best way to do this?

= item_step_fields.fields_for :responses do |response_fields, i|

div.show.button
fieldset.response.translatable

ul-tabs-content
  li-simple#{i}Tab
    = response_fields.label :response_text, "Response Text"
    = response_fields.text_area :response_text, rows: "5", class: "wysiwyg", style: 'width:100%'
    = render partial: 'readable_text/form_fields', locals: { fields: response_fields, style: 'width:100%' }
    = response_fields.text_field :sort_order, class: "input-text small", placeholder: "Sort Order"
  div
    = render partial: 'images/form_fields', locals: { fields: response_fields }
  div.correctness
    = response_fields.label :is_correct do
      = response_fields.check_box :is_correct, class: "is_correct"
      = "Correct"
    div.rationale
      = response_fields.label :rationale
      = response_fields.text_area :rationale, rows: "5", style: 'width:100%'

@clm-a
Copy link
Author

clm-a commented Mar 6, 2012

The main idea is to iterate over each child object

= question.responses.each_with_index do |response, i|

then, inside this loop, to build each mini-form for these children, giving the child you want to deal with to the builder

   = question_form_builder.fields_for :responses, response do |response_form_builder|
     = response_form_builder.check_box :is_correct

Hope it helps, but I'm not so familiar with haml nor foundation so implementation may depends regarding what you want to do :) I can help with questions, but it's hard for me to deal with this kind of rough stuff blindly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment