3

我有一个带有嵌套表单的 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));
}
4

3 回答 3

4

您是否尝试过添加:

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

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

于 2010-06-21T02:27:36.210 回答
3

我和你有完全一样的问题。我通过删除线来修复它

validates_associated :parent_model

来自嵌套模型(在您的情况下为 Trip 模型)。

于 2011-07-24T14:16:27.317 回答
0

我有类似的问题。从父模型中删除 attr_accessible 行对我有用。我看到您的 Itenerary 模型已经没有那条线,所以这可能对您没有帮助;但可能会帮助别人。

于 2010-05-02T11:27:29.473 回答