Michael Choi
Michael Choi

Reputation: 134

Adding new field in edit page using dynamic nested forms

I'm trying to create a form with dynamic add and remove nested model fields. I've pretty much followed ryanb's railcast (http://railscasts.com/episodes/197-nested-model-form-part-2) with some minor changes to make it compatible with Rails 4.0

The only thing that doesn't work is adding new fields on the edit page. Right now, if I add a new field, it takes on the structure and data of a previously existing field.

So for example, let's say that I create a question "FooBarBaz" with the the answers "foo" and "bar". I realize I'm missing "baz", so I go in to edit the question, and when I click new field, the page now shows the answers "foo", "bar", "foo", "bar". Instead, I want "foo", "bar" and an empty field.

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

Upvotes: 0

Views: 1394

Answers (1)

Michael Choi
Michael Choi

Reputation: 134

Realized it was a problem with the application_helper.rb. More specifically it should be,

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

where new_object was missing.

Upvotes: 0

Related Questions