首页 > 解决方案 > Rails 以管理员身份循环并删除对象

问题描述

以下循环显示与特定项目关联的每个评论,并允许评论所有者(用户)编辑或删除评论。这工作得很好。

现在我希望管理员能够删除评论。唯一的问题是,当我单击删除时...与特定项目相关的所有评论都将被删除,而不仅仅是那个。

知道如何解决这个问题吗?

<% @comments.each do |comment| %>
  <% if current_user == comment.user %>
    <%= link_to "Delete", destroy_item_comment_path(comment.item_id, comment.id),
                method: :delete, data: { confirm: I18n.t("comment_delete_alert")}, :class=>"glyphicon glyphicon-trash" %>     
  <% elsif current_admin %>
    <%= link_to "Delete", admin_destroy_item_comment_path(comment.item_id, comment.id),
                method: :delete, data: { confirm: I18n.t("comment_delete_alert")}, :class=>"glyphicon glyphicon-trash" %>
  <% end %>
<% end %>

控制器方法:

before_action :find_comment, only: [:destroy]

def destroy
  @comment.destroy
  redirect_back(fallback_location: root_path)
  flash[:notice] = "Comment has been deleted"
end

def find_comment
  @comment = @item.comments.find(params[:id])
end

更新 1

以管理员身份删除评论时的服务器日志

 Comment Load (0.9ms)  SELECT "comments".* FROM "comments" WHERE "comments"."user_id" = $1  [["user_id", 213]]
 (0.2ms)  BEGIN
  SQL (0.4ms)  DELETE FROM "comments" WHERE "comments"."id" = $1  [["id", 14]]
  SQL (0.4ms)  DELETE FROM "comments" WHERE "comments"."id" = $1  [["id", 15]]
  SQL (0.3ms)  DELETE FROM "comments" WHERE "comments"."id" = $1  [["id", 16]]
   (1.2ms)  COMMIT
 Completed 302 Found in 14123ms (ActiveRecord: 36.3ms)

标签: ruby-on-railsruby

解决方案


我的预感是您的路线配置不正确。你可以打

rails routes

检查 admin_delete_comment_path 配置。

尝试改变

admin_destroy_item_comment_path(comment.item_id,comment.id)

至:

destroy_item_comment_path(commend.item_id, comment.id)

推荐阅读