Rails Nested Forms Attributes not saving if Fields Added with jQuery

Posted by looloobs on Stack Overflow See other posts from Stack Overflow or by looloobs
Published on 2010-04-10T13:40:47Z Indexed on 2010/04/10 13:43 UTC
Read the original article Hit count: 602

Hi I have a rails form with a nested form. I used Ryan Bates nested form with jquery tutorial and I have it working fine as far as adding the new fields dynamically.

But when I go to submit the form it does not save any of the associated attributes. However if the partial builds when the form loads it creates the attribute just fine. I can not figure out what is not being passed in the javascript that is failing to communicate that the form object needs to be saved.

Any help would be great.

class Itinerary < ActiveRecord::Base
  accepts_nested_attributes_for :trips
end

itinerary/new.html

<% form_for ([@move, @itinerary]), :html => {:class => "new_trip" } do |f| %>

  <%= f.error_messages %>
  <%= f.hidden_field :move_id, :value => @move.id %>
  <% f.fields_for :trips do |builder| %>
    <%= render "trip", :f => builder %>
  <% end %>
<%= link_to_add_fields "Add Another Leg to Your Trip", f, :trips %>

<p><%= f.submit "Submit" %></p>

<% end %>

application_helper.rb

 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, :f => builder)
  end
  link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
 end

application.js

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));
}

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about jQuery