Last active
May 26, 2023 20:24
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= 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