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
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
<%= render :partial => 'task', :collection => @project.tasks %>
<%= add_task_link "Add a task" %>
projects/_task.erb
<%= fields_for "project[task_attributes][]", task do |task_form| %>
Task: <%= task_form.text_field :name %>
<%= link_to "remove", "#", :class => 'remove_task'
<% end %>
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'));
});
});