Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<table>
<%= f.fields_for :daughters do |daughters_form| %>
<tr>
<td>
Daughter Name:
</td>
<td>
<%= daughters_form.text_field :name %>
</td>
<td>
<%= daughters_form.hidden_field :_destroy %>
<%= link_to 'remove', '#', class: 'remove-fields' %>
</td>
</tr>
<% end %>
</table>
<%= form_for(father) do |f| %>
<% if father.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(father.errors.count, "error") %> prohibited this father from being saved:</h2>
<ul>
<% father.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<%= link_to_add_fields "Add a daughter", f, :daughters %>
<br>
<table>
<%= f.fields_for :daughters do |daughters_form| %>
<tr>
<td>
Daughter Name:
</td>
<td>
<%= daughters_form.text_field :name %>
</td>
<td>
<%= daughters_form.hidden_field :_destroy %>
<%= link_to 'remove', '#', class: 'remove-fields' %>
</td>
</tr>
<% end %>
</table>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
module ApplicationHelper
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
end
$ ->
$('form').on 'click', '.remove-fields', (event) ->
$(this).prev('input[type=hidden]').val('1')
$(this).closest('table').hide()
event.preventDefault()
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).after($(this).data('fields').replace(regexp, time))
event.preventDefault()
<ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"Kk59weYpfZRfHYrvZka2CSfZ5CSjOuy2a2fjZjpKhVG+ALWkuQVNo/MJnaEpMiErEwPPO/KxzJvQ7dFSHtcQLg==", "father"=>{"name"=>"Bob", "daughters_attributes"=>{"1467509946084"=>{"daughters"=>{"name"=>"Sally", "_destroy"=>""}}}}, "commit"=>"Create Father", "controller"=>"fathers", "action"=>"create"} permitted: false>
Unpermitted parameter: daughters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment