0

我正嘗試使用動態添加和刪除嵌套模型字段來創建表單。我幾乎跟着ryanb的railcast(http://railscasts.com/episodes/197-nested-model-form-part-2)進行了一些小的修改,使其與Rails 4.0兼容。使用動態嵌套表單在編輯頁面中添加新字段

唯一不起作用的是在編輯頁面添加新字段。現在,如果我添加一個新字段,它將採用先前存在字段的結構和數據。

因此,舉個例子,假設我用答案「foo」和「bar」創建了一個問題「FooBarBaz」。我意識到我錯過了「baz」,所以我進入編輯問題,當我點擊新字段時,頁面現在顯示答案「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)); 
} 

回答

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失蹤。

相關問題