使用动态嵌套表单在编辑页面中添加新字段

时间:2013-11-01 17:41:02

标签: ruby-on-rails dynamic ruby-on-rails-4 simple-form nested-forms

我正在尝试使用动态添加和删除嵌套模型字段来创建表单。我几乎跟随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”和空场。

的routes.rb

resource :questions do
  resource :answers
end

question.rb

has_many :answers, dependent: :destroy
accepts_nested_attributes_for :answers, allow_destroy: true

answer.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

questions.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));
}

1 个答案:

答案 0 :(得分:0)

意识到这是application_helper.rb的一个问题。更具体地说,它应该是,

fields = f.simple_fields_for association, new_object, child_index: "new_#{association}" do |builder|
  render(association.to_s.singularize + "_fields", :f => builder)
end

缺少 new_object