Rails custom Twitter Bootstrap modal for delete method, Problem with callback

前端 未结 1 1873
你的背包
你的背包 2021-02-06 18:58

Following code does destroy records as intended, but the callback is inherited from one modal to the next one. So while a record is properly deleted, Rails keeps looking to dele

相关标签:
1条回答
  • 2021-02-06 19:23

    Turns out it is a bad idea to fiddle with the native delete method/callback for various reasons. My workaround solution is as follows.

    Have a "delete" button in your view, with some JS data values:

    #delete button in view template
    link_to "delete", "#", 
       :class => "delete_post", 
       "data-id" => YOUR_POST_ID, 
       "data-controls-modal" => "YOUR_MODAL_LAYER",
           #more bootstrap options here…
    

    Bootstrap opens the modal window. Inside that, have another "delete" button with "remote" set, so the action will use JS.

    #delete button in modal window
    link_to "delete", post_path(0), 
       :method => :delete, 
       :class => "btn primary closeModal", 
       :remote => true  
    

    CloseModal is another :class for me to know when to close the bootstrap modal window. I've put an additional function for that in my application.js. Note, the default path has a nil value, we'll attach the real post ID to be deleted via JS in the next step via the "data-id" param:

    #application.js 
    $('a.delete_post').live('click', function(){
        _target = $(this).data('id');
        $('#YOUR_MODAL_LAYER .primary').attr('href', '/posts/' + _target);
    });
    

    The destroy action in our Posts controller will use JS to render an animation for the deleted post:

    #posts_controller.rb
    def destroy
        @post = Post.find(params[:id])
        @post.destroy
        respond_to do |format|
           # format.html { redirect_to(posts_url) }
           format.js { render :content_type => 'text/javascript' }
        end
    end
    

    Insert here effects as you please. In this example we are simply fading out the deleted post:

    #views/posts/destroy.js    
    $("div#post-<%= params[:id] %>").fadeOut();
    

    Altogether this works really smoothly!

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