Delete with AJAX in Rails
One of the biggest pains in Rails when you're just starting out is that there is no AJAX, and it can be laborious to add AJAX to your site. The easiest AJAX snippet to add, by far, is a simple AJAX delete button.
If your running Rails, you've seen the code below (Pretend we have a table holding all of our comments)
%table
%tr
%th User
%th Comment
%th
- @comments.each do |comment|
%tr
%td= comment.user.name
%td= comment.text
%td= link_to 'Delete', comment_path(comment), method: :delete
How annoying is it that clicking that Delete
button will cause the page to reload every time?
Using the following jQuery, we can add an AJAX delete to any model in our project, instantly.
$('a.destroy').click(function(e) {
e.preventDefault();
destroyable = $(this).closest('.destroyable');
url = $(this).attr('href') + '.json';
$.ajax(url, {
type: 'DELETE',
complete: function() {
$(destroyable).fadeOut(100);
}
});
});
And then just change your view accordingly
%table
%tr
%th User
%th Comment
%th
- @comments.each do |comment|
%tr.destroyable
%td= comment.user.name
%td= comment.text
%td= link_to 'Delete', comment_path(comment), class: 'destroy'
See how this is extendable to literally any scaffold? It's only about 15 extra lines of code and it's a huge UX improvement.
Cheers!
-Brian