如果使用 jQuery 添加字段,Rails 嵌套表单属性不会保存

2024-06-19

我有一个带有嵌套表单的 Rails 表单。我使用 Ryan Bates 嵌套表单和 jquery 教程,并且就动态添加新字段而言,它工作得很好。

但是当我提交表单时,它不会保存任何关联的属性。但是,如果在表单加载时构建部分,则它会很好地创建属性。我无法弄清楚 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));
}

您是否尝试过添加:

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

当然,您还需要为您的行程模型添加字段。如果不知道这些,我就会猜测它们是什么。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果使用 jQuery 添加字段,Rails 嵌套表单属性不会保存 的相关文章

随机推荐