Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westonganger/ec76e91c0567b17e78c6d2b44e548dda to your computer and use it in GitHub Desktop.
Save westonganger/ec76e91c0567b17e78c6d2b44e548dda to your computer and use it in GitHub Desktop.
Rails fields_for and nested attributes: How to add or remove without cocoon gem
<%= form_for @post do |f| %>
<div class="comments-wrapper">
<% f.fields_for :comments do |f2| %>
<%= render "comment_fields", f: f2 %>
<% end %>
</div>
<button type="button" class="add-comment">Add Comment</button>
<script>
$(function(){
$(".add-comment").click(function(){
var uniqueId = crypto.randomUUID();
// OR
var uniqueId = Date.now().toString(36) + Math.random().toString(36).substring(2);
// OR
var uniqueId = $(".comment-container").length;
var html = "#{j f.fields_for(:comments, @post.comments.new, child_index: 'REPLACE_ID'){|f2| render('comment_fields', f: f2) }}";
html.replace(/REPLACE_ID/g, uniqueId);
$(".comments-wrapper").append(html);
});
$(document).on("click", ".delete-comment", function(){
var container = $(this).closest(".comment-container");
container.find("input[name$='[_destroy]']").val("1");
container.hide();
});
});
</script>
<% end %>
-------------------------------------------------------------------------------------------------
### _comment_fields.html.erb
<div class="comment-container">
<!-- Other comment fields here -->
<%= f.hidden_field :_destroy %>
<button type="button" class="delete-comment">Delete Comment</button>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment