我已经实现了基于Ryan Bates Railscast的多态评论,到目前为止一切正常,但我试图确定删除操作的范围,以便只有评论的所有者可以删除他们自己的评论和所有者commentable可以删除任何评论。我不确定如何实现这一目标。
有什么想法吗?
这是我的 CommentsController :
class CommentsController < ApplicationController
before_filter :authenticate_member!
before_filter :load_commentable
def index
@comments = @commentable.comments
@comment = @commentable.comments.new
end
def new
@comment = @commentable.comments.new
end
def create
@comment = @commentable.comments.new(params[:comment])
@comment.member = current_member
if @comment.save
redirect_to :back
else
render :new
end
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
if @comment.destroy
redirect_to :back
else
format.html { redirect_to :back, alert: 'You can\'t delete this comment.' }
end
end
private
# def load_commentable
# resource, id = request.path.split('/')[1,2] # photos/1/
# @commentable = resource.singularize.classify.constantize.find(id)
# Photo.find(1)
# end
# alternative option:
def load_commentable
klass = [Status, Medium].detect { |c| params["#{c.name.underscore}_id"] }
@commentable = klass.find(params["#{klass.name.underscore}_id"])
end
end
答案 0 :(得分:1)
您可以按如下方式设置destroy方法:
def destroy
@comment = Comment.find(params[:id])
if @comment.user == current_user
@comment.destroy
format.html { redirect_to :back, alert: "Comment Successfully destroyed" }
else
format.html { redirect_to :back, alert: 'You can\'t delete this comment.' }
end
end
如果您想允许管理员删除任何评论,您可以更改
if @comment.user == current_user
到
if @comment.user == current_user || current_user.admin?