2013-11-21 43 views
0

我已經實現了基於Ryan Bates Railscast的多態註釋,並且所有內容目前工作正常,但我試圖限定刪除操作,以便只有註釋的所有者才能刪除它們自己的評論和評論的所有者可以刪除任何評論。我不知道如何做到這一點。Rails多態註釋範圍刪除操作

任何想法?

這裏是我的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

您使用的是cancan嗎?另外,你如何知道'user''擁有'commentable'? – CDub

回答

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?