Rails Nested Forms Attributes not saving if Fields Added with jQuery

大憨熊 提交于 2019-12-13 11:37:58

问题


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

回答1:


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.




回答2:


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).




回答3:


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.



来源:https://stackoverflow.com/questions/2613576/rails-nested-forms-attributes-not-saving-if-fields-added-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!