我有型號Post
其中has_many :relics
和Relic
其中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>