Skip to content

Instantly share code, notes, and snippets.

@ccashwell
Last active November 29, 2018 22:32
Show Gist options
  • Save ccashwell/4217820 to your computer and use it in GitHub Desktop.
Save ccashwell/4217820 to your computer and use it in GitHub Desktop.
CanCan Authorization: Restrict resources by request format JSON
# Lock down controller actions with CanCan based on request format.
class Ability
include CanCan::Ability
def initialize(user, format=nil)
user ||= User.new
can :index, Model if format == "application/json"
end
end
class SomeController < ApplicationController
authorize_resource
def index
respond_to do |format|
format.html do
@something = Model.find_something
end
format.json do
render json: Model.find_something.to_json
end
end
end
protected
def current_ability
@_current_ability ||= Ability.new(current_user, request.format)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment