Last active
November 29, 2018 22:32
-
-
Save ccashwell/4217820 to your computer and use it in GitHub Desktop.
CanCan Authorization: Restrict resources by request format JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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