Reputation: 658
I'm using CanCan for a role-based admin-system in an application I am building. It is sort of a template for webshops, so an admin can have a different role in each webshop he/she has access to. For example: In webshop 1 he is a moderator, and in webshop 2 he is an editor.
So what I need to do in CanCan's ability Class is check what kind of role the current user has in the current shop (current_shop). I wrote this:
class Ability
include CanCan::Ability
def initialize(admin)
if admin.supervise?(current_shop, controller_gsub)
can :manage, :all
elsif admin.manage?(current_shop, controller_gsub)
can :manage, :all
elsif admin.access?(current_shop, controller_gsub)
can :read, :all
end
end
end
The problem is I can't seem to call the current_shop method from the Ability Class, because I get this error:
undefined local variable or method `current_shop' for #<Ability:0x104df38b0>
Does anybody know how to go about this? Thanx in advance!
Upvotes: 1
Views: 273
Reputation: 10823
Actually you can't access any of controller methods into the Ability class. What is the business logic? Admin can really manage every single thing if he is a supervisor for a current_shop? or probably he can manage only the things, where he manages the shop?
Then it would be nice to have smth like:
class Ability
include CanCan::Ability
def initialize(admin)
can :manage, :all do |obj|
admin.supervise?(obj.shop) || admin.manage?(obj.shop)
end
can :read, :all do |obj|
admin.access?(obj.shop)
end
end
end
PS i'm not quite sure the block would work with :all
, and it's not quite logical to call .shop
on an unknown class, but that's just to show the way, it's easy enough to list the models for which this will be used
Upvotes: 2