Thanks to @tadman, I ended up approaching this problem from a completely different perspective, and my issue is now resolved.
As explained in this excellent Engine Yard tutorial, I moved away from the respond_to
and format.js
approach entirely. I'm now instead using the AJAX approach that apparently the Rails Core Team prefers -- that is:
My View:
<p data-js-comment-id=<%= c.id %> class="blank_links" style="margin-top:-12px;">
<%= c.body %>
<%= link_to blog_post_comment_path(@blog_post,c), remote: true, method: :delete,
data: { confirm: "Are you sure?" } do %>
<%= fa_icon "trash" %>
<% end %>
</p>
My controller:
class CommentsController < ApplicationController
def destroy
@blog_post = BlogPost.find(params[:blog_post_id])
@comment = Comment.find(params[:id])
@comment.delete
render json: @comment
end
end
My /app/assets/javascripts/blog_posts.js
file (which I renamed from originally being /app/assets/javascripts/blog_posts.coffee
because I don't use CoffeeScript):
$(document).on('turbolinks:load', function() {
$("[data-js-comment-id]").on("ajax:success", function(event, data, status, xhr){
var comment_id = xhr.responseJSON.id;
$( "#comment-" + comment_id ).fadeOut(650);
get_default_success_toastr("Comment deleted!", "And just like that, pffft. It's gone!");
});
});
Note above the $(document).on('turbolinks:load', function() {
line. That's very important, as noted here and here.
And finally, my application.js
file:
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require activestorage
//= require_tree .
//= require popper
//= require bootstrap-sprockets
//= require toastr
The reason that I included the application.js
file above is because: (a) the order in which you require the libraries appears to make a difference, and (b) notice that I removed rails-ujs
Works perfect!