我有一个带有嵌套表单的 rails 表单。我在 jquery 教程中使用了 Ryan Bates 嵌套表单,就动态添加新字段而言,它运行良好。
但是当我去提交表单时,它不会保存任何相关的属性。但是,如果在表单加载时部分构建它会很好地创建属性。我无法弄清楚什么没有在 javascript 中传递,无法传达表单对象需要保存。
任何帮助都会很棒。
class Itinerary < ActiveRecord::Base
accepts_nested_attributes_for :trips
end
行程/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
应用程序.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));
}