I am using rails 5, rails_admin, devise and cancancan.
Everything works correctly, but when there is access denied, it shows a 'You are not authorized to access this page' error screen.
I want to redirect to root_path, I've been searching and I only found that I have to write in app/controllers/application_controller.rb this code:
class ApplicationController < ActionController::Base
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_path, :alert => exception.message
end
end
And I did, but I am still in the error message when not authorised. It does not redirect.
I think the rest of the code must be ok, because it works, but not redirecting to anywhere.
#config/initializers/rails_admin.rb
config.authorize_with :cancan
config.current_user_method(&:current_user)
.
#app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.admin
can :access, :rails_admin # only allow admin users to access Rails Admin
can :dashboard
can :manage, :all
else
can :read, :all # allow everyone to read everything
end
end
end
I saw more people asking the same, but all of them are without answers. I found one with 3 answers, but I don't understand the accepted solution because it really do not explain any solution: Cancan + Devise rescue_from not catching exception