皱74 Complex Forms Part 2
1218 ワード
See how to use Javascript and RJS to add and remove form fields dynamically.This episode will build up the previous episode allowing you to create any number of tasms one form the same time time time project creat.
<!-- layouts/application.rhtml -->
<%= javascript_include_tag :defaults %>
<!-- projects/new.rhtml -->
<div id="tasks">
<%= render :partial => 'task', :collection => @project.tasks %>
</div>
<p><%= add_task_link "Add a task" %></p>
<!-- projects/_task.rhtml -->
<div class="task">
<% fields_for "project[task_attributes][]", task do |task_form| %>
<p>
Task: <%= task_form.text_field :name %>
<%= link_to_function "remove", "$(this).up('.task').remove()" %>
</p>
<% end %>
</div>
# projects_helper.rb
def add_task_link(name)
link_to_function name do |page|
page.insert_html :bottom, :tasks, :partial => 'task', :object => Task.new
end
end