在 Rails 多态注释、ActiveRecord 中实现 Destroy 时遇到问题

Trouble implementing Destroy in Rails Polymorphic Comments, ActiveRecord

我正在构建一个 Rails 应用程序,该应用程序具有一些多态关系,可以正常工作,但是我在执行销毁操作时遇到了问题。评论 table 是多态的 table、主题 has_many :comments 和个人资料 has_many :comments。目前,我正在为从主题显示页面(基本上是一个论坛)删除评论的能力而苦苦挣扎。我创建了一个 edit_comment_path 并且可以通过评论控制器成功编辑和更新评论,但是当我尝试删除时,@comment = Comment.find(params[:id]) 它一直在寻找 Subject.id 而不是 Comment.id?要删除的 link 似乎是正确的,所以我有点困惑。请看下面的代码。任何建议或改进也将不胜感激!

views/comments/_comment.html.erb

<% commentable.comments.each do |comment| %>
  <div>
    <hr>
    <% if commentable == @subject %>
      <p><%= comment.body %>  |  Posted by <%= comment.user.email %>, <%= time_ago_in_words(comment.created_at) + ' ago' %></p>

      <% if comment.user == current_user %>
        <%= link_to "Edit", edit_comment_path(comment, subject: 'subject') %>
        <%= link_to "Delete", comment_path, method: :delete %>
      <% end %>
    <% else %>
      <p><<%= comment.title %></p>
      <p><%= comment.body %> </p>
    <% end %>
  </div>
<% end %>

comments_controller.rb

class CommentsController < ApplicationController

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

  def create
    @comment = @commentable.comments.new(comment_params)
    @comment.user_id = current_user.id
    if @comment.save
      redirect_to @commentable, notice: "Successfully Posted!"
    end
  end

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

  def update
    @comment = Comment.find(params[:id])
    if @comment.update(comment_params)
      redirect_to @comment.commentable, notice: "Comment was updated."
    end
  end

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

  private
  def comment_params
    params.require(:comment).permit(:title, :body)
  end
end

views/subjects/show.html.erb

<h1><%= @subject.title %></h1>
<p>Created by: <%= @subject.user.email %>, <%= time_ago_in_words(@subject.created_at) + ' ago' %></p>


<%= render partial: 'comments/comment', locals: {commentable: @subject} %>
<%= render partial: 'comments/form', locals: {commentable: @subject} %>

config/routes.rb

Rails.application.routes.draw do
  resources :locations, only: [:show, :destroy, :edit, :update]
  resources :comments, only: [:show, :edit, :update, :destroy]

  resources :subjects, only: [:index, :show] do
    resources :comments, module: :subjects
  end
  resources :profiles do
    resources :subjects, module: :profiles
    resources :locations, module: :profiles
    resources :comments, module: :profiles
  end
  resource :session, only: [:new, :create, :destroy]
  resources :users, only: [:new, :create, :show]
  root "home#index"

end

如有任何反馈,我们将不胜感激

乍一看好像

<%= link_to "Delete", comment_path, method: :delete %>

应该是:

<%= link_to "Delete", comment_path(comment), method: :delete %>

我假设问题是 params[:id] 传递给您的评论#destroy 是主题的 id 而不是评论的 id

此外,您的销毁方法应该类似于:

def destroy
    comment = Comment.find(params[:id])
    comment.destroy
    redirect_to somewhere
end