i have followed the railscasts episode on nested forms(part 1 and 2) and having difficulty with adding fields using jquery, however when i click the remove fields link, the field gets removed. Here is the code.
In my question model i have
class Question < ActiveRecord::Base has_many :tags, :class_name => "Tag", :dependent => :destroy, :foreign_key => "question_id" accepts_nested_attributes_for :tags, :reject_if => lambda { |a| a[:keyword].blank? }, :allow_destroy => true
In my tag model i have
class Tag < ActiveRecord::Base attr_accessible :keyword, :question_id belongs_to :question, :class_name => "Question", :foreign_key => 'question_id' end
In my question form i have
<%= form_for @question, :url => { :controller => "questions", :action => "create" } do |f| %> <%= f.label(:name, "Request Question:") %> <%= f.text_field(:name, :size => 72, :maxlength => 120) %><br /> <%= f.fields_for :tags, :url => { :controller => "tags", :action => "create" } do |builder| %> <%= render "tag_fields", :f => builder %> <% end %> <p><%= link_to_add_fields "Add new tag", f, :tags %></p> <% end %>
In my tag_fields partial
<p class="fields"> <%= f.label(:keyword, "Keywords:") %> <%= f.text_field(:keyword, :size => 20, :maxlength => 25) %> <%= link_to_remove_fields "remove", f %> </p>
In application_helper.rb
module ApplicationHelper def link_to_remove_fields(name, f) f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)") end 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 end
Then finally in my application.js
function remove_fields(link) { $(link).prev("input[type=hidden]").val("1"); $(link).closest(".fields").hide(); } function add_fields(link, association, content) { var new_id = new Date().getTime(); var regexp = new RegExp("new_" + association, "g") $(link).parent().before(content.replace(regexp, new_id)); }
I have checked to see if files are included in page source. The jquery works because other parts of my app are working. I do not get any error when i click add new tag. I have looked at other solutions, but none work for me. I cannot seem to add a field. Thanks for the help