Working with CanCanCan - nsarno/knock GitHub Wiki
Knock do not automatically work with CanCanCan out of the box. Kindly refer to the code below to make it work:
app/models/ability.rb
class Ability
include Knock::Authenticable
include CanCan::Ability
def initialize(current_user)
if current_user.has_role? :admin
can :create, EligibleItem
end
end
end
app/controllers/application_controller.rb
class ApplicationController < ActionController::API
include Knock::Authenticable
rescue_from CanCan::AccessDenied do |exception|
render json: { error: 'You are not authorized to perfom this action' }, status: :forbidden
end
end
In you controller:
def create
options = {}
options[:is_collection] = false
item = EligibleItem.new(permitted_eligible_items_params)
authorize! :create, item <-- this triggers authorization
if item.save
render json: EligibleItemSerializer.new(item, options).serialized_json
else
render json: { errors: item.errors }, status: :not_found
end
end
Result:
Thanks! ✨