I am using rialscasts #74 as a guide.
I am trying to dynamically add form fields via a text-link. In the railscast episode he achieves it very nicely using the followin
The current RailsCasts/ASCIICasts are #196 (see http://asciicasts.com/episodes/196-nested-model-form-part-1) & 197 which have been updated for Rails3.
Ryan Bates has also created a gem called nested_form (see https://github.com/ryanb/nested_form) which handles much of this for you. He has has also created examples of complex nested forms using Prototype, jQuery, and his nested form gem; you can find a link on the nested_forms page.
Good stuff!
ya I was going to say -- that is a very old railscast and is using both outdated practices and an old framework. I'm gonna try to help you out.
layouts/application.erb
<%= javascript_include_tag :defaults %>
projects/new.erb
<div id="tasks">
<%= render :partial => 'task', :collection => @project.tasks %>
</div>
<p><%= add_task_link "Add a task" %></p>
projects/_task.erb
<div class="task">
<!-- I think this part should still work -->
<%= fields_for "project[task_attributes][]", task do |task_form| %>
<p>
Task: <%= task_form.text_field :name %>
<!-- We're going to be defining the click behavior with unobtrusive jQuery -->
<%= link_to "remove", "#", :class => 'remove_task'
</p>
<% end %>
</div>
projects_helper.rb
def add_task_link(name)
# This is a trick I picked up... if you don't feel like installing a
# javascript templating engine, or something like Jammit, but still want
# to render more than very simple html using JS, you can render a partial
# into one of the data-attributes on the element.
#
# Using Jammit's JST abilities may be worthwhile if it's something you do
# frequently though.
link_to name, "#", "data-partial" => h(render(:partial => 'task', :object => Task.new)), :class => 'add_task'
end
public/javascripts/application.js
$(function(){
// Binds to the remove task link...
$('.remove_task').live('click', function(e){
e.preventDefault();
$(this).parents('.task').remove();
});
// Add task link, note that the content we're appending
// to the tasks list comes straight out of the data-partial
// attribute that we defined in the link itself.
$('.add_task').live('click', function(e){
e.preventDefault();
$('#tasks').append($(this).data('partial'));
});
});