I can easily delete the entries of post
synchronously
in rails application by following code:
views
<% @post.each do |post| %>
<tr>
<td colspan="3"><%= link_to 'Destroy', post, :method => :delete, :confirm => 'Are you sure?', :class => 'btn btn-mini btn-danger' %></td>
</tr>
<% end %>
Controller class
def destroy
@post = Post.find(params[:id])
@post.destroy
respond_to do |format|
format.html redirect_to(posts_url) }
format.xml { head :ok }
end
end
This works fine. How make this destroy
process async
. So, that I will not required to add route
or refresh the page
.
Edit
Adding more explanation
Task is to make destroy
method async
. So that the client will not wait for the response and destroy
method will run in background async
. Also the destroy method has no guaranteed completion time.
Another example could be: I have to delete multiple post at a time.
For making
Async
request you needAjax
and basicjavascript
to remove the code of<td>
.First change your
views
code to :Above code says that it will call the
destroy
method ofPostController
class. Now you need to make some changes indestroy
method ofcontroller
classAbove code is pretty understandable, except why we use
respond_to
. In rails we can render the data in two ways:Javascript
HTML
we will use
javascript
to render the code because it's a easy way to remove the<td>
tag with the help ofID
.Now we need a
js
file to render the response ofdestroy
method. To do this adddestroy.js.erb
in the same folder of yourviews
.Add this following code in
destroy.js.erb
:You are done! I will recommend you to read : http://www.gotealeaf.com/blog/the-detailed-guide-on-how-ajax-works-with-ruby-on-rails
Try
remote: true
option,posts.js.erb
Please change as you need. I am just guessing.