【问题标题】:Adding new field in edit page using dynamic nested forms使用动态嵌套表单在编辑页面中添加新字段
【发布时间】:2013-11-01 17:41:01
【问题描述】:

我正在尝试创建一个具有动态添加和删除嵌套模型字段的表单。我已经非常关注 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

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

【问题讨论】:

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


    【解决方案1】:

    意识到这是 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 丢失的地方。

    【讨论】:

      猜你喜欢
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多