开发者

Rails Nested Forms Attributes not saving if Fields Added with jQuery

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开发者_C百科 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));
}


Have you tried adding:

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

Of course you would then need to add the fields for your Itinerary model also. Without knowing those I would be guessing what they are.


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

validates_associated :parent_model

from the nested model (in your case the Trip model).


I was having similar issue. Removing the attr_accessible line from parent model did the trick for me. I see that your Itenerary model is already devoid of that line, so this might not help you; but might help someone else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜