Search code examples
ruby-on-railsdeviseactiveadmincancan

Activeadmin : undefined method `access_denied'


I use rails 5.0 cancan 1.6.10 devise 4.2.0 Activeadmin

I regulary have this error in newrelic :

NoMethodError: undefined method `access_denied' for #<Admin::FollowupsController:0x007f112917d270>

In active_admin.rb i set :access_denied in the config :

  config.on_unauthorized_access = :access_denied

How can I remove this error and have a good management of redirection for access_denied instead of a 500 ?


Solution

  • As you have configured ActiveAdmin to use :access_denied method on unauthorized access, you need to define this method in application_controller.rb and redirect the user from the page they don't have permission to access to a resource they have permission to access. You may also display the error message in the browser. A typical example:

    class ApplicationController < ActionController::Base
      protect_from_forgery with: :exception
    
      def access_denied(exception)
        redirect_to admin_root_path, alert: exception.message
      end
    end
    

    An example of redirecting to the home page for HTML requests and returning 403 Forbidden for JSON requests:

    def access_denied(exception)
      respond_to do |format|
        format.json { head :forbidden, content_type: 'text/html' }
        format.html { redirect_to main_app.root_url, notice: exception.message }
      end
    end
    

    If you prefer to return the 403 Forbidden HTTP code, create a public/403.html file and render it like so:

    def access_denied(exception)
      render file: Rails.root.join('public', '403.html'), 
             status: 403, 
             layout: false
    end