Dynamically add fields in rails with out nested attributes Dynamically add fields in rails with out nested attributes ruby-on-rails ruby-on-rails

Dynamically add fields in rails with out nested attributes


So here is what I came up with...here are my two models...

class Skill < ActiveRecord::Base  belongs_to :tag  attr_accessible :tag_id, :weightendclass Tag < ActiveRecord::Base  has_many :skills  attr_accessible :nameend

I'm calling a partial from app/views/skills/_form.html.erb and using a js tag to add new fields. Also note that I am re-rendering the partial, then hiding it in the last div tag.

  <div id="skillSet">    <%= render partial: "skills_form" %>  </div>  <a href="javascript:;" id="addNewTag">Add New Tag</a>  <div class="actions">    <%= f.submit %>  </div><% end %><div class="hide" id="new_skills_form">  <%= render partial: "skills_form", locals: {skill: false} %></div>

The partial is pretty simple. All I am doing here is storing the values in an array...

<div class="skillsForm">  <%= label_tag 'tag' %>  <%= text_field_tag 'tags[]' %>  <%= label_tag 'weight' %>  <%= text_field_tag 'weights[]' %></div>

...here is the javascript...real straight forward, just say when #addNewTag is clicked, appeand #new_skills_form to #skillSet

$(document).ready(function(){  $("#addNewTag").click(function(){    $("#skillSet").append($("#new_skills_form").html());  });});

...and finally the controller action decontructs the arrays, and saves them...

def create    @skill = Skill.new(params[:skill])    tags = params[:tags]    weights = params[:weights]    tags.each_with_index do |tag, index|      tag = Tag.create :name => tag      Skill.create :tag_id => tag.id, :weight => weights[index]    end  end