Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

Protecting controller of nested association with polymorphic parent? #1027

Open
MarkMurphy opened this issue Feb 23, 2015 · 1 comment
Open

Comments

@MarkMurphy
Copy link

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
Copy link

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants