ruby-on-rails - 删除帖子的评论会删除整个帖子
问题描述
当我尝试删除对帖子的评论时,我最终会删除整个帖子。
评论控制器
class CommentsController < ApplicationController
def create
@micropost = Micropost.find_by(id: params[:micropost_id])
@comment =
@micropost.comments.create(params[:comment].permit(:name,:body))
if @comment.save
flash[:success] = "Comment Posted"
end
redirect_to request.referrer
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to request.referrer
end
end
评论视图
<li>
<ol class="microposts">
<% @post.comments.each do |comments| %>
<li>
<article class="article-container-full">
<%= comments.name%>
<hr>
<%= comments.body %>
<hr>
<p class="posted-time"> Posted <%=
time_ago_in_words(comments.created_at) %> ago</p>
<p>
<%= link_to 'Delete', @comment, :method => :delete, data:
{confirm: 'Are you sure?'}%>
</p>
</article>
<br>
</li>
</ol>
<% end %>
</li>
评论路线
micropost_comments GET
/microposts/:micropost_id/comments(.:format)
comments#index
POST
/microposts/:micropost_id/comments(.:format)
comments#create
new_micropost_comment GET
/microposts/:micropost_id/comments/new(.:format) comments#new
edit_micropost_comment GET
/microposts/:micropost_id/comments/:id/edit(.:format)
comments#edit
micropost_comment GET
/microposts/:micropost_id/comments/:id(.:format)
comments#show
PATCH
/microposts/:micropost_id/comments/:id(.:format)
comments#update
PUT
/microposts/:micropost_id/comments/:id(.:format)
comments#update
DELETE
/microposts/:micropost_id/comments/:id(.:format)
comments#destroy
微贴模型:
class Micropost < ApplicationRecord
has_many :comments, dependent: :destroy
belongs_to :user
validates :user_id, presence: true
validates :headline, presence: true, length: { maximum: 200 }
validates :content, presence: true, length: { maximum: 10000 }
end
评论型号:
class Comment < ApplicationRecord
belongs_to :micropost
end
Microposts Controller 中的销毁方法只是以防万一:
def destroy
@micropost.destroy
flash[:success] = "Post deleted"
redirect_to request.referrer || current_user
end
我有一种感觉,我错过了一些非常小的东西,但我只能看到它。它不仅删除了评论,还删除了整个帖子以及与之相关的所有其他内容。
解决方案
首先,你还没有@comment
在任何地方初始化。这就是您收到此错误的原因。
另一件事是您不应该comments
在 do..end 循环中使用该变量。因为它,对评论的迭代使它变得单一。
尝试跟随,
<li>
<ol class="microposts">
<% @post.comments.each do |comment| %>
<li>
<article class="article-container-full">
<%= comment.name%>
<hr>
<%= comment.body %>
<hr>
<p class="posted-time"> Posted <%=
time_ago_in_words(comment.created_at) %> ago</p>
<p>
<%= link_to "Delete Comment", [@post ,comment], :confirm => "Are you sure?", :method => :delete%>
</p>
</article>
<br>
</li>
</ol>
<% end %>
</li>
推荐阅读
- javascript - 选择选择选项时使用 Javascript 添加 css 样式
- python - 使用 ftplib python 创建一个带有特殊字符的文件
- kubernetes - 使用 kubeadm 重置工作节点何时重新加入主节点
- paypal-ipn - 任何想法为什么我的 PayPal IPN 侦听器自发地开始抛出错误?
- mysql - mysql对象数组比较项目
- python - 条件语句不执行?
- powershell - 如何解决运行 Invoke-sqlcmd 命令以使用 Invoke-SQLCMD 和 Powershell 6 连接到 Azure Datawarehouse 的错误?
- mysql - 使用 JOIN 在重复值上查询 sql SUM 仅 1 个值
- c - 如何在 C 函数中分配三重指针的内存
- c - 这个空字符打印的输出是什么?