Ajax comments not working in Rails 3.0.3
In layouts/application.html.erb. I have:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Some title</title>
<%= stylesheet_link_tag 'application' %>
<%= stylesheet_link_tag 'blueprint/print', 'media' => 'print' %>
<%= javascript_include_tag 'jquery', 'jquery-ui-1.8.2.custom', 'jquery.colorbox-min', 'jquery.corner', 'jquery.countdown.min', 'jquery.uploadFileThis',
'jquery.ui.core', 'jquery.ui.mouse', 'jquery.ui.position', 'jquery.ui.slider', 'jquery.ui.widget', 'jquery.ui.datepicker',
'ajaxupload', 'jwplayer', 'swfobject', 'flowplayer-3.2.4.min', 'rails',
'application', :cache => true %>
<%= csrf_meta_tag %>
</head>
<body>
.....
In my view, I have:
<%= link_to 'delete', song_comment_path(comment.media, comment), :confirm => 'Are you sure?', :method => :delete, :remote => true %>
My Comments controller, destroy method looks like:
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
respond_to do |format|
format.html { redirect_to(root_path) }
format.xml { head :ok }
format.js { }
end
end
When I click this link, I get a pop-up box saying "Are you sure?". I click OK. I have a destroy.js.erb file in /views/comments. Inside this file, I have:
alert('Inside destroy.js.erb');
// and some code to hide the comment element
The comment is deleted, but not via ajax. It seem开发者_开发技巧s, the link_to goes into comment controller, destroy method. But is responding to respond.html, instead of respond.js. Hence why I don't get the alert('Inside destroy.js.erb');
This all used to work fine when I was still using Rails 3.0.0, until I decided to upgrade:
- to Rails 3.0.3,
- from query 1.4.0 to 1.4.4 (http://jquery.com/),
- and update latest rails.js (https://github.com/rails/jquery-ujs)
Why isn't format.js being called? Why is Rails still trying to call format.html?
If you look at the actual link generated by the link_to
, you'll find that even though you're using ajax to send the delete request, you're still sending a request to /song/:song_id/comment/:comment_id
. Because there's no format, Rails will default to .html
.
To make sure the request goes to the right format, you can add a :format
option to your link_to:
<%= link_to 'delete', song_comment_path(comment.media, comment, :format => :js), :confirm => 'Are you sure?', :method => :delete, :remote => true %>
This should now give you a link like this: /song/:song_id/comment/:comment_id.js
精彩评论