在Rails 4中使用Ajax绑定新创建的项目的销毁链接

时间:2015-03-25 19:55:33

标签: ruby-on-rails ajax

我正在Rails 4应用程序中实现注释。 我想创建注释并删除注释以使用Ajax远程工作。

除了新添加的评论的删除链接不起作用外,它工作正常。

为新创建的项目制作删除链接的最佳方法是什么?

/ views / posts / show.html.haml

    .post
        %h1= @post.name

    %h2 Comments
    = render 'comments/form', comment: @comment
    %ul#comments
      = render 'comments/comment', :collection => @post.comments, :as => :comment

/views/comments/_form.html.haml

    .comment-form
      = simple_form_for comment, :remote => true do |f|
        = f.input :body, :input_html => { :rows => "2" }, :label => false
        = f.button :submit, :class => "btn btn-primary"

/views/comments/_comment.html.haml

  %li{:"data-id"=>comment.id}
    =comment.body
    %br
    = link_to "Destroy", comment_path(comment), :confirm => "Are you sure?", :method => :delete, remote: true, :class=>'link_comment_delete'

/views/comments/destroy.js.rb

  $('#comments li[data-id=<%=@comment.id%>]').hide();

/views/comments/create.js.rb

  $("#comments").append("<li><%= escape_javascript render @comment %></li>");

  // ??? what to write here to make Delete link work

1 个答案:

答案 0 :(得分:1)

我遇到了相同的情况,最后使用delete重新考虑.closest视图,而不是与data-id绑定,因此您可以执行以下操作:< / p>

$("a.link_comment_delete").on('ajax:complete',function(e) {
    $(this).closest('div.comment.body [or whatever class / id you are using]').fadeOut(100)
    });