Ok, finally got this figured out!
Form
<%= form_for @survey do |f| %>
<% if @survey.errors.any? %>
<div class="error_messages">
<h2><%= pluralize(@survey.errors.count, "error") %> prohibited this survey from being saved:</h2>
<ul>
<% @survey.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<%= f.fields_for :questions do |builder| %>
<%= render 'question_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add Question", f, :questions, :answers %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Helper
module ApplicationHelper
def link_to_add_fields(name, f, association, child_association = nil)
new_object = f.object.send(association).klass.new
if child_association
3.times{ new_object.send(child_association).build } #Builds 3 Answers
#new_object.send(child_association).build #Builds 1 Answer
end
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
The child_association = nil
and
if child_association
3.times{ new_object.send(child_association).build } #Builds 3 Answers
#new_object.send(child_association).build #Builds 1 Answer
end
are there because adding new answers via the link also uses the same helper, but since answers doesn't accept any nested attributes it would fail. Adding the above allows you to use the same helper for both and stay DRY.