I've implemented polymorphic commenting based off the Ryan Bates Railscast and everything is working correctly so far, but I'm trying to scope the delete action so that only the owner of the comment can delete their own comments and the owner of the commentable can delete any comment. I'm not sure how to make this happen.

Any ideas?

Here's my 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
有帮助吗?

解决方案

You could set up your destroy method as follows:

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 you want to allow your admin to delete any comments, you can change

if @comment.user == current_user

to

if @comment.user == current_user || current_user.admin?
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top