I am using CanCanCan for authorization purposes. Basically what I want to happen is non-logged in users can access Home#Index
, but they need to be logged in for Home#Dashboard
.
I have this route:
get 'dashboard', to: 'home#dashboard', as: :dashboard
This is my HomeController
:
class HomeController < ApplicationController
authorize_resource except: [:index]
skip_authorization_check only: [:index]
layout 'marketing', only: [:index]
def index
end
def dashboard
end
end
This is my application_controller.rb
:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
check_authorization :unless => :devise_controller?
rescue_from CanCan::AccessDenied do |exception|
respond_to do |format|
format.json { head :forbidden }
format.html { redirect_back(fallback_location: root_path, flash: { danger: exception.message }) }
end
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:accept_invitation, keys: [:first_name, :last_name, :phone])
end
end
However, when I go to /dashboard
, this is the error I get:
NameError - uninitialized constant Home:
activesupport (5.0.0.1) lib/active_support/dependencies.rb:550:in `load_missing_constant'
activesupport (5.0.0.1) lib/active_support/dependencies.rb:203:in `const_missing'
activesupport (5.0.0.1) lib/active_support/inflector/methods.rb:268:in `block in constantize'
activesupport (5.0.0.1) lib/active_support/inflector/methods.rb:266:in `constantize'
activesupport (5.0.0.1) lib/active_support/core_ext/string/inflections.rb:66:in `constantize'
What could be causing this?
Edit 1
After some debugging, I now realize that it seems to be related to the fact that the action I am authorizing
isn't backed by an ActiveRecord resource.
In other words, once I add :dashboard
to the exception
list, like so:
authorize_resource except: [:index, :dashboard]
skip_authorization_check only: [:index, :dashboard]
It works. The page loads like a charm.
So I guess the real issue is, how do I authorize/lock down a resource that is not an ActiveRecord model?