我正在构建一个具有一些多态关系的Rails应用程序,但是我在实现销毁操作时遇到了麻烦。 Comment表是多态表,Subject has_many :comments
和profile has_many :comments
。我现在正努力从主题节目页面删除评论(基本上是一个论坛)。我创建了一个edit_comment_path并可以通过注释控制器成功编辑和更新注释,但是当我尝试删除时,@comment = Comment.find(params[:id])
它一直在寻找Subject.id而不是Comment.id?删除链接似乎是正确的,所以我有点困惑。请参阅下面的代码。任何建议或改进也将不胜感激!
<% 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 %>
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
<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} %>
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
非常感谢任何反馈
答案 0 :(得分:1)
从快速浏览看起来像
<%= link_to "Delete", comment_path, method: :delete %>
应该是:
<%= link_to "Delete", comment_path(comment), method: :delete %>
我认为问题在于,params[:id]
传递给您的评论#stroy是主体的ID而不是评论的ID
此外,您的destroy方法应该类似于:
def destroy
comment = Comment.find(params[:id])
comment.destroy
redirect_to somewhere
end