如果用jQuery添加字段,则Rails嵌套表单属性无法保存 [英] Rails Nested Forms Attributes not saving if Fields Added with jQuery
问题描述
我有一个带有嵌套表单的Rails表单.我在RjQuery教程中使用了Ryan Bates嵌套表格,就动态添加新字段而言,它工作得很好.
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.
但是当我提交表单时,它不会保存任何关联的属性.但是,如果部分在窗体加载时生成,则它会很好地创建属性.我无法弄清楚无法传达需要保存表单对象的javascript中没有传递的内容.
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.
任何帮助都会很棒.
class Itinerary < ActiveRecord::Base
accepts_nested_attributes_for :trips
end
itinerary/new.html
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
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
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));
}
推荐答案
您是否尝试添加:
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.
这篇关于如果用jQuery添加字段,则Rails嵌套表单属性无法保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!