Dynamically add fields in rails with out nested attributes

后端 未结 1 333
北海茫月
北海茫月 2021-01-31 12:36

I am in the early stages of creating an app, and am just putting some basic code in place. Here is the current code...

app/views/cards/front.html.erb

&         


        
相关标签:
1条回答
  • 2021-01-31 13:00

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

    class Skill < ActiveRecord::Base
      belongs_to :tag
      attr_accessible :tag_id, :weight
    end
    
    class Tag < ActiveRecord::Base
      has_many :skills
      attr_accessible :name
    end
    

    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
    
    0 讨论(0)
提交回复
热议问题