2

我有一个可评论的用户模型:

class User < ActiveRecord::Base
  acts_as_commentable

在用户控制器中,我正在获取如下评论:

@comments = @user.comments.recent.page(params[:notifications]).per(10)

在用户显示视图中,有一个部分呈现评论:

<% @comments.each do |comment| %>
  <p><%= time_ago_in_words(comment.created_at) %> ago</p>
  <h4><%= comment.comment %></h4>
<% end %>

我无法在部分中添加链接或按钮以允许用户删除(最好通过 AJAX 调用)单个评论。我知道这是基本的 Rails,但我在这里完全迷失了。

更多信息:

class Comment < ActiveRecord::Base
  include ActsAsCommentable::Comment
  belongs_to :commentable, :polymorphic => true
  default_scope -> { order('created_at ASC') }
  belongs_to :user
end

我真的很感激一个简洁而完整的答案。

我没有包含 routes.rb 因为目前评论仅在回调其他用户操作时创建。因此没有关于 routes.rb 中的评论的信息

4

1 回答 1

0

像往常一样,解决方案很简单:

路线.rb:

resources :comments, only: :destroy

用户控制器:

def show
  @comments = @user.comments.recent.page(params[:notifications]).per(10)
end

意见/用户/_comments.html.erb:

<% @comments.each do |comment| %>
  <span id="<%= comment.id %>">
    <p><%= time_ago_in_words(comment.created_at) %> ago</p>
    <h4>
      <%= comment.comment %>
      <%= link_to comment, method: :delete, remote: true %>
    </h4>
  </span>
<% end %>

评论控制器:

def destroy
  @user = current_user
  @comment = Comment.destroy(params[:id])
  respond_to do |format|
    format.html { redirect_to user_path(@user) }
    format.xml  { head :ok }
    format.js
  end
end

意见/评论/destroy.js.erb:

$('#<%= @comment.id %>').remove();
于 2014-03-31T11:44:41.523 回答