ryanb / cancan

Authorization Gem for Ruby on Rails.
MIT License
6.27k stars 784 forks source link

Protecting controller of nested association with polymorphic parent? #1027

Open MarkMurphy opened 9 years ago

MarkMurphy commented 9 years ago

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 
karlingen commented 9 years ago

https://github.com/CanCanCommunity/cancancan