Note that there are some explanatory texts on larger screens.

plurals
  1. PORails Nested Model Form: Add nested model fields dynamically through JavaScript using Prototype
    text
    copied!<p>I'm following a Railscast <a href="http://railscasts.com/episodes/197-nested-model-form-part-2" rel="nofollow">tutorial</a> from Jan 2010.</p> <p>I'm implementing Project lists that has_many Items.</p> <p>The code to dynamically add Item fields is not working.</p> <h3>views/projects/_form.html.erb</h3> <pre><code>&lt;%= form_for(@project) do |f| %&gt; &lt;p&gt; &lt;%= f.label :title %&gt;&lt;br /&gt; &lt;%= f.text_field :title %&gt; &lt;/p&gt; &lt;% f.fields_for :items do |builder| %&gt; &lt;%= render "item_fields", :f =&gt; builder %&gt; &lt;% end %&gt; &lt;p&gt;&lt;%= link_to_add_fields "+item", f, :items %&gt;&lt;/p&gt; &lt;div class="actions"&gt;&lt;%= f.submit %&gt;&lt;/div&gt; &lt;% end %&gt; </code></pre> <h3>views/projects/_item_fields.html.erb</h3> <pre><code>&lt;div class="fields"&gt; &lt;p&gt; &lt;%= f.label :name, "item" %&gt; &lt;%= link_to_remove_fields "remove", f %&gt;&lt;br /&gt; &lt;%= f.text_field :name %&gt; &lt;/p&gt; &lt;/div&gt; </code></pre> <h3>helpers/application_helper.rb</h3> <pre><code> def link_to_remove_fields(name, f) f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)") end def link_to_add_fields(name, f, association) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, :child_index =&gt; "new_#{association}") do |builder| render(association.to_s.singularize + "_fields", :f =&gt; builder) end link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")) end </code></pre> <h3>public/javascripts/application.js</h3> <pre><code>function remove_fields(link) { $(link).previous("input[type=hidden]").value = "1"; $(link).up(".fields").hide(); } function add_fields(link, association, content) { var new_id = new Date().getTime(); var regexp = new RegExp("new_" + association, "g") $(link).up().insert({ before: content.replace(regexp, new_id) }); } </code></pre> <p>The original Jan 2010 code is available at <a href="https://github.com/ryanb/railscasts-episodes/tree/master/episode-197/surveysays" rel="nofollow">https://github.com/ryanb/railscasts-episodes/tree/master/episode-197/surveysays</a></p> <p>The difference in the implementation is that my code only has 1 layer (Project / Item). The tutorial has more nesting (Survey / Question + Answer).</p> <p>What do I need to change in the javascript or other parts to make the add new Item functionality work?</p> <p>Thank you</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload