title: Rails - fields_for and javascript to dynamically add and remove fields in a form (railscasts ep. 196-197)
body: <p><strong>UPDATE</strong></p>
  
  <p>Thank you for your answer.</p>
  
  <p>But If I remove</p>
  
  <pre><code>for requested_role in @project.requested_roles
  </code></pre>
  
  <p>from the partial, then I can't access to the requested_role.role value, because I don't have the parameter X obtained from the code</p>
  
  <pre><code>for X in @projects.requested_roles 
  </code></pre>
  
  <p>and I can't write X.role</p>
  
  <p>How can I access this value without using for or .each to scroll the requested_roles of the project?</p>
  
  <p><strong>END UPDATE</strong></p>
  
  <hr>
  
  <p>I've a problem with a social network I'm developing with Ruby on Rails. I followed the <a href="http://railscasts.com/episodes/196-nested-model-form-part-1" rel="nofollow">railscasts 196</a> and <a href="http://railscasts.com/episodes/197-nested-model-form-part-2" rel="nofollow">197</a> to create a form with fields_for and to add fields dinamically with javascript, but I have 2 major problems.</p>
  
  <p>A User can create a Project and this Project must have 1+ Requested_roles.
  When I open the project edit page to change the roles, if there are N requested_roles for the project, I see N*N forms to change the requested_roles. So if I have 2 requested_roles (for example Director and Producer) I see 4 select fields, Director - Producer - Director -Producer. They are repeated N times. And I can't modify them because I can have max 1 requested_role of each type. It's fine if I have only 1 requested_role (because 1x1=1)</p>
  
  <p>Project.rb</p>
  
  <pre><code>class Project &lt; ActiveRecord::Base
  attr_accessible :title, :requested_roles_attributes, :video, :num_followers, :num_likes
  
  belongs_to :user
  
  has_many :requested_roles, dependent: :destroy
  accepts_nested_attributes_for :requested_roles, :reject_if =&gt; lambda { |a| a[:ruolo].blank? }, :allow_destroy =&gt; true
  </code></pre>
  
  <p>Requested_role.rb</p>
  
  <pre><code>class RequestedRole &lt; ActiveRecord::Base
  attr_accessible :role, :project_id 
  
  belongs_to :project
  </code></pre>
  
  <p>Projects_controller.rb</p>
  
  <pre><code>class ProjectsController &lt; ApplicationController
  
  def new
    @project= Project.new
    @requested_role= @project.requested_roles.build    
  end   
  </code></pre>
  
  <p>Projects/edit.html.erb</p>
  
  <pre><code>&lt;div class="row"&gt;
   &lt;div class="span6 offset3"&gt;
    &lt;%= form_for(@project) do |f| %&gt;
      &lt;%= render 'shared/error_messages', object: f.object%&gt; 
  
      &lt;%= f.label :title, "Project title" %&gt;
      &lt;%= f.text_field :title %&gt;
  
      &lt;%= f.fields_for :requested_roles do |builder| %&gt;
            ciao
           &lt;%= render 'requested_role', :f =&gt; builder   %&gt;
  
      &lt;% end %&gt;
  
      &lt;div class="fields"&gt;
      &lt;p&gt;&lt;%= link_to_add_fields "Add requested role", f, :requested_roles %&gt;&lt;/p&gt;
      &lt;/div&gt;
  
      &lt;/br&gt;
  
      &lt;%= f.submit 'Apply changes', class: 'btn btn-large btn-primary' %&gt;
  
    &lt;% end %&gt;
  &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>I think that the error is in this view (Projects/edit):</p>
  
  <pre><code>    &lt;%= f.fields_for :requested_roles do |builder| %&gt;
            ciao
           &lt;%= render 'requested_role', :f =&gt; builder   %&gt;
      &lt;% end %&gt;
  </code></pre>
  
  <p>this code, even without the partial, lead to a N-times repeated requested_roles. In fact, without the partial _requested_role, we have N "ciao", but we should have only one.</p>
  
  <p>projects/_requested_role.html.erb</p>
  
  <pre><code>&lt;% if @project.requested_roles.any? %&gt;
      &lt;p&gt;Modifica ruoli richiesti &lt;/p&gt;
  &lt;%end%&gt;
  &lt;%= @project.requested_roles.count %&gt;
  &lt;% for requested_role in @project.requested_roles %&gt;
      &lt;div class="fields"&gt;
  
      &lt;p&gt;
      &lt;p&gt;Requested role: &lt;%= role_to_string(requested_role.role) %&gt;&lt;/p&gt;
  
      &lt;%= f.label :role, "Modify role" %&gt;
      &lt;%= f.select :role, options_for_select([["Regista",1],["Sceneggiatore", 2],["Direttore della fotografia", 3], ["Operatore",4],
                                        ["Fonico", 5], ["Montatore", 6], ["Truccatrice",7], ["Costumista",8], ["VFX Artist",9],
                                        ["Produttore", 10], ["Attore",11], ["Attrice",12], ["Grip/Runner",13]], :selected =&gt; requested_role.role) %&gt;
  
  
      &lt;%= link_to_remove_fields "remove", f %&gt;    #dinamically remove a field
      &lt;/p&gt;
  
  &lt;% end %&gt;
  
  &lt;/div&gt;
  </code></pre>
  
  <p>Can you help me please? I can't figure out where the error is. Thank you in advance.</p>
  
  <p>The other problem is related to the links to dinamically delete and add requested_roles (javascript-jquery).</p>
  
  <p>If I have 3 requested_roles (9 select fields instead of 3 because of the error that I mentioned before) and I delete (through link_to_remove_fields) the last one there's no problem. But if I delete the first one, the fields and even the submit button below it disappear and I can't modify the roles or submit the changes.</p>
  
  <p>When I add (through link_to_add_fields) a new role and I already have, for example, 2 requested_roles (Director, Producer), when I click on the link to add the new requested_role another bug occurres. Instead of a select field to choose the role, a copy of the 2 existing select fields (Director, Producer) appears.</p>
  
  <p>application_helper.rb</p>
  
  <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, :f =&gt; builder)
    end
    link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
  end
  </code></pre>
  
  <p>Application.js</p>
  
  <pre><code>function remove_fields(link) {
      $(link).prev("input[type=hidden]").val("1");
      $(link).closest(".fields").hide();
  }
  
  
  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));
  }
  </code></pre>
  
  <p>I can't understand what goes wrong. If you have some idea can you give me some advice? Thank you very much.</p>
  
  <p>Dario</p>