I have a parent model (paper) and a nested child model (tape) and want to create multiple child with a parent in same time without using any gems. The input fields of tape should be dynamically added through clicking “+”.
If I write “3.times { @paper.tapes.build }” in controller, I can create 1 paper and 3 tapes in same time. But if how many times the input field should be added is depend on the user (if user click "+" 10 times, 1 parent model and 10 child model should be saved in one time), how should I modify the code?
Here is my codes. Paper Model
has_many :tapes
accepts_nested_attributes_for :tapes, allow_destroy: true
Tape Model
belongs_to :paper, optional: true
Controller
def new
@paper = Paper.new
3.times { @paper.tapes.build }
end
def create
@paper = Paper.new(paper_params)
@paper.user_id = current_user.id
if @paper.save
redirect_to action_list_paper_path(@paper.id)
else
render 'new'
end
end
Viewer
<%= nested_form_for(@paper) do |f| %>
<div class="container">
<%= stylesheet_link_tag 'papers', media: 'all', 'data-turbolinks-track': 'reload' %>
<div class= "paper_form">
<div class="col-md-6">
<%= f.label(:content, "Name") %>
<%= f.text_area :content %>
</div>
</div>
</div>
<div class="tape_form">
<%= f.fields_for :tapes do |tape| %>
<div id="input_pluralBox">
<div id="input_plural">
<div class="col-md-4">
<%= tape.label :label %>
<%= tape.text_field :label %>
</div>
</div>
<input type="button" value="+" class="add pluralBtn">
<input type="button" value="-" class="del pluralBtn">
</div>
</div>
<% end %>
</div>
</div>
<% end %>
Javascript (The input column “label” will be added with "+" through javascript).
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("click", ".add", function() {
$(this).parent().clone(true).insertAfter($(this).parent());
});
$(document).on("click", ".del", function() {
var target = $(this).parent();
if (target.parent().children().length > 1) {
target.remove();
}
});
</script>