如何确保用户只能删除自己的评论?轨道

时间:2018-02-09 02:03:18

标签: ruby-on-rails ruby devise

我在一堆问题下面有评论,现在我的代码在每个人的评论下都显示了删除评论链接,而不仅仅是发表评论的用户。如何解决此问题,以便用户只能删除自己发表的评论?我正在使用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

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

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
  belongs_to :user
end

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

2 个答案:

答案 0 :(得分:1)

更改您的观点:

<% if current_user && current_user == comment.user %>

更改您的控制器:

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

答案 1 :(得分:0)

如果您将视图中的<% if current_user %>更改为<% if current_user && current_user == comment.user %>,则只会为该评论的所有者显示删除链接。

您还应该检查current_user是否与@comment.user控制器方法中的destroy相匹配。