I am trying to destroy a comment through Ajax. In my app, my comment model uses a polymorphic association. The comment deletes successfully (in the database) using the code below. However, when I call the destroy.js.erb, it doesn’t do anything and I think the problem is that the dom_id doesn’t match the HTML id, so it is not updating. I think I am experiencing the same thing that @mu_is_too_short articulated in the answer to this question. I need help with how to solve this though. I do not know if the solution involves a) somehow passing the local variable comment to the destory.js.erb or b) another solution.
routes.rb
resources :feeds do
resources :comments
end
destroy.js.erb
$('#<%= dom_id(@comment) %>')
.fadeOut ->
$(this).remove()
_comment.html.erb
<div id=<%= dom_id(comment) %> class="comment">
<em>on <%= comment.created_at.strftime('%b %d, %Y at %I:%M %p') %></em>
<%= link_to "Remove", [@commentable, comment], :method => :delete, :remote => true %>
<%= simple_format comment.content %>
</div>
feeds/show.html.erb
<div id="comments">
<%= render @comments %>
</div>
Comments controller
class CommentsController < ApplicationController
def create
@comment = @commentable.comments.new(params[:comment])
if @comment.save
respond_to do |format|
format.html { redirect_to @commentable }
format.js
end
else
render :new
end
end
def destroy
@comment = Comment.find(params[:id])
@commentable = @comment.commentable
if @comment.destroy
respond_to do |format|
format.html { redirect_to @commentable }
format.js
end
end
end
end
Feeds controller
class FeedsController < ApplicationController
def show
@feed = Feed.find(params[:id])
@commentable = @feed
@comments = @commentable.comments
@comment = Comment.new
end
end
By the looks of it, @comment will contain a comment when you get to destroy.js.erb, as you set it in the controller immediately before that, so I do not think it has anything to do with the referenced answer. I wonder if this is being caused by the lack of quotes around your id here:
<div id=<%= dom_id(comment) %> class="comment">… I suspect if you correct this, and any other relevant HTML validation errors, it will start working.