cancan icon indicating copy to clipboard operation
cancan copied to clipboard

Protecting controller of nested association with polymorphic parent?

Open MarkMurphy opened this issue 10 years ago • 1 comments

I have a Comment model which belongs_to :commentable, polymorphic: true association. I'm wondeirng how to setup the controller, here's what I have to far:

class CommentsController < APIController

  before_action :load_commentable
  load_and_authorize_resource :through => :commentable

  # GET .../comments
  def index
    @comments = @commentable.comments
  end

  # GET .../comments/:id
  def show
    @comment = @commentable.comments.find(params[:id])
  end

  # POST .../comments
  def create
    @comment = @commentable.comments.build(comment_params)

    if @comment.save
      # ...
    else
      # ...
    end
  end

  # PATCH .../comments/:id
  def update
    @comment = @commentable.comments.find(params[:id])

    if @comment.update(comment_params)
      # ...
    else
      # ...
    end
  end

  # DELETE .../comments/:id
  def destroy
    @comment = @commentable.comments.find(params[:id])
    @comment.destroy
    # ...
  end

private

  def comment_params
    # ...
  end

  def load_commentable
    params.each do |name, value|
      if name =~ /(.+)_id$/
        @commentable = $1.classify.constantize.find(value)
      end
    end
  end

end 

MarkMurphy avatar Feb 23 '15 19:02 MarkMurphy

https://github.com/CanCanCommunity/cancancan

karlingen avatar Sep 01 '15 16:09 karlingen