Rails Nested Forms Attributes are not saved if fields are added in jQuery

I have a rails form with a nested form. I used the Ryan Bates nested form with the jquery tutorial and I am working great on adding new fields dynamically.

But when I go to submit the form, it does not save any related attributes. However, if the partial assembly when loading the form creates an attribute just fine. I cannot understand what is not being passed in javascript, which does not indicate that the form object should be saved.

Any help would be great.

class Itinerary < ActiveRecord::Base accepts_nested_attributes_for :trips end 

route / 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)); } 
+3
source share
3 answers

Have you tried adding:

 class Itinerary < ActiveRecord::Base attr_accessible :move_id, :trips_attributes accepts_nested_attributes_for :trips end 

Of course, you will also need to add fields to your route model. Without knowing these, I would have guessed what it is.

+4
source

I had the same problem as you. I fixed it by deleting the line

 validates_associated :parent_model 

from a nested model (in your case, a Trip model).

+2
source

I had a similar problem. Removing the attr_accessible line from the parent model did the trick for me. I see that your Itenerary model is already deprived of this line, so this may not help you; but can help someone else.

0
source

All Articles