Search code examples
ruby-on-rails-4activeadmincancan

Activeadmin custom pages and Cancan


I am using Activeadmin and Cancan for user authorization. It works fine on all standard pages, but on custom pages I am struggling to pass values to Cancan’s Abilities. On my custom active admin page I have

 controller do
   prepend_before_filter :filter_method

   def filter_method
     @project = Project.find(params[:id])
     authorize! :show, @project
   end
 end

in Abilities I have

 can :manage, ActiveAdmin::Page, :name => "Project Preview", :poster_id => user.user_id

Now I was hoping that authorize! :show, @project would pass the Project values to cancan, but all I am getting is “undefined method `poster_id' “. I have been playing around with this for hours and am completely stuck so any advice would be greatly appreciated.


Solution

  • You'll need to override the page controller's authorize_access! method; see the ActiveAdmin::PageController implementation for reference.

    ActiveAdmin.register_page "Project Page with Authorization" do
      content do
        # page content
      end
    
      controller do
        private
    
        def find_project
          @project = Project.find(params[:id])
        end
    
        def authorize_access!
          find_project
          authorize! :show, @project
        end
      end
    end
    

    The ability check would then only be checking against Project and not ActiveAdmin::Page:

    can :show, Project, :poster_id => user.user_id
    

    Also note that by default the page view is actually the index controller action and is passed the active_admin_config as the subject for authorization checks.