Ive created a nested model form the RailsCasts Nested Model Form Part 2 example and have it working with Rails 3 and JQuery. Currently, a user can create a new project and click a link to add new tasks, and within each new task, click a link that will allow them to add new assignments to each task. Here's the link to create a new task (the link to create new assignments is similar):
<p><%= link_to_add_fields "Add task", f, :task %></p>
That refers to this helper:
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))end
It works like this: By clicking the link, html is added through JQuery that displays a form field for the task's name and a link that allows a user to add new assignments to the task.
What I'd like to do is have the assignment forms appear alongside the task name field - so that the user does not need to click an additional link to add a new assignments to each task. I can accomplish this when the page first loads through the project controller:
1.times do
task = @product.tasks.build
1.times { task.assignments.build}
end
However, because Im using JQuery to add and remove HTML, the controller won't be called and the forms won't be build when 'adding' new tasks.
Is there a way to 'build' the nested assignment fields automatically (from within the task partial) when the new task field is created?
Here's my partial for the task form that is created when a user clicks the 'new task' link in the form:
<div class = "fields">
<%= f.label :name, "Task name"%>
<%= link_to_remove_fields "remove", f %><br />
<%= f.text_field :name %>
<% f.fields_for :assignments do |builder| %>
<%= render 'assignment_fields', :f => builder %>
<% end %>
<p><%= link_to_add_fields "Add assignments", f, :assignments %></p>