我正在尝试创建一个具有动态添加和删除嵌套模型字段的表单。我已经非常关注 ryanb 的 railcast ( http://railscasts.com/episodes/197-nested-model-form-part-2 ) 做了一些小改动以使其与 Rails 4.0 兼容
唯一不起作用的是在编辑页面上添加新字段。现在,如果我添加一个新字段,它将采用以前存在的字段的结构和数据。
例如,假设我创建了一个问题“FooBarBaz”,答案是“foo”和“bar”。我意识到我缺少“baz”,所以我进入编辑问题,当我单击新字段时,页面现在显示答案“foo”、“bar”、“foo”、“bar”。相反,我想要“foo”、“bar”和一个空字段。
路线.rb
resource :questions do
resource :answers
end
问题.rb
has_many :answers, dependent: :destroy
accepts_nested_attributes_for :answers, allow_destroy: true
答案.rb
belongs_to :question
_form.html.erb
<%= simple_form_for @question do |f| %>
<div class="question">
<%= f.input :name %>
<div class="answer">
<%= f.simple_fields_for :answers do |g| %>
<%= render "answer_fields", f: g %>
<% end %>
<p><%= link_to_add_fields("Add Question", f, :answers) %></p>
</div>
</div>
<% end %>
application_helper.rb
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.simple_fields_for association, child_index: "new_#{association}" do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, "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));
}