How to apply abilities to a non-restful controller in cancan
I'm new to rails and for the life of me I don't "get" cancan.
I've read this tutorial but can't figure out how to apply instructions to my situation.
In the cancan wiki there is:
- an AdminController
- a roll_logs action
In the ability class is says:
can :roll, :logs if user.admin?
I don't get what the :roll and :logs symbols have to do with the controller and the action?
All I want to do is say, if a user is an admin, give them access to the AdminController actions, otherwise don't, is this possible?
Yes this is possible.
can :roll, :logs if user.admmin?
means that when calling authorize! :roll, :logs an unauthorized exception gets thrown if the user isn't an admin.
So it doesn't have anything to do with a controller or an action, untill you make it so.
If you have a logs_controller for example with an action roll you could do something like this.
class LogsController < ApplicationController def roll authorize! :roll, :logs # Rest of the roll functionality. end
So in your example, you want to give users who are admin permission to access all admin controller actions.
You can achieve this like this.
class Ability include CanCan::Ability def initialize(user) can(:manage, :admin) if user.admin? end end
class AdminController < ApplicationController authorize_resource :class => false def foo end def bar end end
This will make sure that only admins can access the foo and bar actions of the admin_controller.
The :class => false statement means that you are not authorizing a resource, which is what we want since you are not for example authorizing a certain post or comment. You are just authorizing actions on a controller.