Skip to content

How To: Check Ownership

Elliott Roche edited this page Aug 19, 2022 · 1 revision

If you don't need Cancan gem, you can code implement checking ownership method like below code. https://github.com/x1wins/tutorial-rails-rest-api#authorize

  • ApplicationController
    class ApplicationController < ActionController::API
      def is_owner user_id
        unless user_id == @current_user.id
          render json: nil, status: :forbidden
          return
        end
      end
    
      def is_owner_object data
        if data.nil? or data.user_id.nil?
          return render status: :not_found
        else
          is_owner data.user_id
        end
      end
    end
  • How to Use is_owner_object in Your PostsController
    class PostsController < ApplicationController
        before_action only: [:update, :edit, :destroy] do
          is_owner_object @post ## your model object
        end
    end
Clone this wiki locally