Rails循环并以管理员身份删除对象

问题描述 投票:0回答:1

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

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

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

<% @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-rails ruby
1个回答
0
投票

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

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)
© www.soinside.com 2019 - 2024. All rights reserved.