2011-09-27 68 views
1

我正在使用Rails 3.1 Jquery Ajax演示應用程序在這裏列出https://github.com/samnang/ajax_rails31_demo。我正在嘗試添加代碼以刪除評論。我修改了comments_controller.rb並添加了一個銷燬操作。我還添加了一個指向app/views/_comment.html.erb的鏈接,以包含Destroy鏈接。我能夠將評論刪除,評論計數減1,但評論部分不會更新刪除條目。只有在頁面刷新後頁面才能正確顯示。這裏是我的代碼Rails 3.1 jquery Ajax CRUD操作

應用程序/控制器/ comments_controller.rb

class CommentsController < ApplicationController 
    respond_to :html, :js 

    def index 
    @comments = Comment.all 
    end 

    def create 
    @comment = Comment.new(params[:comment]) 
    @comment.save 

    respond_with @comment, :location => comments_url 
    end 

    def destroy 
    @comment = Comment.find(params[:id]) 
    @comment.destroy 

    respond_with @comment, :location => comments_url 
    end 
end 

應用程序/意見/評論/ index.html.erb

<% title "Comments for Ajax in Rails 3.1" %> 

<div id="comments_count"><%= comments_count %></div> 

<div id="comments"> 
    <%= render @comments %> 
</div> 

<h3>Add your comment:</h3> 

<%= form_for Comment.new, :remote => true do |f| %> 
<%= f.error_messages %> 
    <p> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
    </p> 
    <p> 
    <%= f.label :content, "Comment" %><br /> 
    <%= f.text_area :content, :rows => '12', :cols => 35 %> 
    </p> 
    <p><%= f.submit %></p> 
<% end %> 

應用程序/視圖/評論/ _comment.html.erb

<div class="comment"> 
    <strong><%= comment.name %></strong> 
    <em><%= comment.created_at.strftime('%b %d, %Y at %I:%M %p') %></em> 
    <%= simple_format comment.content %> 
    <%= link_to "Destroy", comment,:remote => true, :confirm => "You Sure", :method => :delete %> 
</div> 

應用程序/ vews /評論/ create.js.coffee

$('<%= escape_javascript(render(:partial => @comment))%>') 
    .appendTo('#comments') 
    .hide() 
    .fadeIn() 

$('#new_comment')[0].reset() 

$('#comments_count').html '<%= comments_count %>' 

應用/視圖/評論/ destroy.js.coffee

$('#new_comment')[0].reset() 

$('#comments_count').html '<%= comments_count %>' 

的破壞的jquery部是我相信我在搞亂。如何重新加載部分以刪除已刪除的評論?

回答

2

我更新了Github上的示例以支持銷燬操作。在你的例子中,你沒有刪除你的destroy.js.coffee中的dom元素。再看看完整的代碼上Github或看看下面的片段:

應用程序/意見/評論/ _comment.html.erb

<div id=<%= dom_id(comment) %> class="comment"> 
    <strong><%= comment.name %></strong> 
    <em>on <%= comment.created_at.strftime('%b %d, %Y at %I:%M %p') %></em> 
    <%= link_to "Remove", comment, :method => :delete, :remote => true %> 
    <%= simple_format comment.content %> 
</div> 

應用程序/意見/評論/ destroy.js.coffee

$('#comments_count').html '<%= comments_count %>' 

$('#<%= dom_id(@comment) %>') 
    .fadeOut -> 
    $(this).remove()