2014-06-23 44 views
2

我有型號Post其中has_many :relicsRelic其中belongs_to :post。我有新的職位表,從那裏我可以創建帖子的遺物(多),以及(它的工作原理):如何動態添加新的嵌套字段通過JS在Rails中形成?

new行動posts_controller.rb

@post_relics = [@post.relics.build]*2 

_form.html.haml

= f.fields_for :relics, @post_relics do |r| 
    .more.group 
    .photo 
     = link_to 'Insert photo', '#', data: {toggle: 'upload'} 
     = r.file_field :photo, accept: 'image/*' 
    .fileds 
     = r.label :title 
     = r.text_field :title 
     = r.label :description 
     = r.text_field :description 

我的目標是添加'添加更多'按鈕,它將提供有效輸入名稱和ID的.more div副本,我該怎麼做?

上面的代碼渲染在:

<div class='more group'> 
    <div class='photo'> 
    <a data-toggle="upload" href="#">Insert photo</a> 
    <input accept="image/*" id="post_relics_attributes_0_photo" name="post[relics_attributes][0][photo]" type="file" /> 
    </div> 
    <div class='fileds'> 
    <label for="post_relics_attributes_0_title">Title</label> 
    <input id="post_relics_attributes_0_title" name="post[relics_attributes][0][title]" type="text" value="" /> 
    <label for="post_relics_attributes_0_description">Description</label> 
    <input id="post_relics_attributes_0_description" name="post[relics_attributes][0][description]" type="text" value="" /> 
    </div> 
</div> 
<input id="post_relics_attributes_0_id" name="post[relics_attributes][0][id]" type="hidden" value="6" /> 
<div class='more group'> 
    <div class='photo'> 
    <a data-toggle="upload" href="#">Insert photo</a> 
    <input accept="image/*" id="post_relics_attributes_1_photo" name="post[relics_attributes][1][photo]" type="file" /> 
    </div> 
    <div class='fileds'> 
    <label for="post_relics_attributes_1_title">Title</label> 
    <input id="post_relics_attributes_1_title" name="post[relics_attributes][1][title]" type="text" /> 
    <label for="post_relics_attributes_1_description">Description</label> 
    <input id="post_relics_attributes_1_description" name="post[relics_attributes][1][description]" type="text" /> 
    </div> 
</div> 

回答

0

正確的答案是由某個用戶給出的,但有人刪除了這個答案 - 太糟糕了。答案是使用Cocoon gem,其中一切都已經實現。

0

下面是使用jQuery一個快速的解決方案:http://jsfiddle.net/M4b9D/9/

function addMore() { 
    var newdiv = $(".more_group:last").clone(); 
    var newid = Number(newdiv.attr('id').replace(/post_relics_attributes_(\d+)/, "$1")) + 1; 

    newdiv.attr('id', "post_relics_attributes_" + newid) 

    $.each(newdiv.find(":input"), function() { 
     var thisname = $(this).attr('id'); 
     thisname = thisname.replace(/\d+/, newid); 

     $(this).attr('name', thisname); 
     $(this).attr('id', thisname); 
     $(this).val(''); 
    }); 

    $("#groups").append(newdiv); 

} 

基本上,它只是創建一組的div內的最後一個div的副本,更新該div內每個輸入的ID /名稱/值。我對你的元素的命名方式起了一點作用,使得這種寫法更容易一些,並且添加了一個組合div,所以會有一些東西來附加新的div。

相關問題