Rails remote delete and update view through Ajax

后端 未结 1 1748
一个人的身影
一个人的身影 2021-02-04 09:49

In the past, whenever I wanted to update a part of my view through Ajax, I\'ve done the following:

  1. create a partial out of the part I want to update and give it a
1条回答
  •  盖世英雄少女心
    2021-02-04 10:08

    Thanks to this page I found the proper way to do it. So simple and effective.

    http://carmennorahgraydean.blogspot.com.es/2012/10/rails-328-ajax-super-basic-example.html

    Update your destroy line in index.html.erb:

    <%= link_to 'Destroy', pony, method: :delete, data: { confirm:
    'Are you sure?' }, :remote => true, :class => 'delete_pony' %>
    

    Create a file, destroy.js.erb, put it next to your other .erb files (under app/views/ponies). It should look like this:

    $('.delete_pony').bind('ajax:success', function() {     
      $(this).closest('tr').fadeOut();
    });
    

    Add format.js { render :layout => false } to your controller:

    respond_to do |format|
     format.html { redirect_to ponies_url }
     format.json { head :no_content }
     format.js   { render :layout => false }
    end
    

    Hope this helps someone else.

    0 讨论(0)
提交回复
热议问题