[英]How to ensure users can only delete their own comments? Rails
I have comments underneath a bunch of questions, right now the code I have shows the delete comment link under everyone's comments not just the user who made the comment. 我在很多问题下都有评论,现在我所拥有的代码在每个人的评论下显示了删除评论链接,而不仅仅是发表评论的用户。 How do I fix this so that users can only delete comments they made themselves?
如何解决此问题,使用户只能删除自己发表的评论? I am using devise gem to authenticate users.
我正在使用devise gem对用户进行身份验证。
<% commentable.comments.each do |comment| %>
<h6 style="text-align:left; margin-bottom: 0px;"><strong><%= comment.user.profile.first_name %> <%= comment.user.profile.last_name %>: </strong></h6>
<p style="text-align:left">
<%= comment.body %>
</p>
<% if current_user %>
<p style="text-align:left; font-size: 12px; margin-top: -10px"><%= link_to 'Delete', [comment.user, comment],
method: :delete,
data: { confirm: 'Are you sure?' } %></p>
<% end %>
<% end %>
comments_controller.rb comments_controller.rb
class CommentsController < ApplicationController
before_action :authenticate_user!
def create
@comment = @commentable.comments.new(comment_params)
@comment.user = current_user
if @comment.save
redirect_back(fallback_location: root_path)
end
end
def update
@comment.update(comment_params)
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
redirect_back(fallback_location: root_path)
end
private
def comment_params
params.require(:comment).permit(:body)
end
end
comment.rb comment.rb
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
belongs_to :user
end
user.rb user.rb
class User < ApplicationRecord
before_create :add_role_to_user
ROLES = %w[admin member].freeze
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :profile
has_many :comments, dependent: :destroy
def add_role_to_user
self.role = 'member'
end
end
Change your view: 改变你的看法:
<% if current_user && current_user == comment.user %>
Change your controller: 更改您的控制器:
def destroy
# ensure user only can find owner comment.
@comment = current_user.comments.find(params[:id])
@comment.destroy
redirect_back(fallback_location: root_path)
end
If you change <% if current_user %>
in your view to <% if current_user && current_user == comment.user %>
then the Delete link will only appear for the owner of that comment. 如果您将视图中的
<% if current_user %>
更改为<% if current_user && current_user == comment.user %>
则“删除”链接仅针对该评论的所有者出现。
You should also check that the current_user
matches the @comment.user
in your destroy
controller method. 您还应该在您的
destroy
controller方法中检查current_user
与@comment.user
匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.