Can you please walk me through the following line of Ruby/Rails?
if user.role? :super_admin
To fit my app, I updated it to:
if user.role? :admin
and that failed, but then I updated it to:
if user.role? == 'admin'
And it works as intended. Why is that?
class Ability
include CanCan::Ability
def initialize(user)
user ||= Use开发者_如何学运维r.new # guest user
if user.role? :super_admin
can :manage, :all
elsif user.role? :product_admin
can :manage, [Product, Asset, Issue]
elsif user.role? :product_team
can :read, [Product, Asset]
# manage products, assets he owns
can :manage, Product do |product|
product.try(:owner) == user
end
can :manage, Asset do |asset|
asset.assetable.try(:owner) == user
end
end
end
end
def role?(role)
return !!self.roles.find_by_name(role.to_s.camelize)
end
if user.role? :super_admin
In this line you call the method role?
on the object user
with the parameter :super_admin
(which is a symbol) and check if the method returns true
.
If the call to user.role? :admin
returns false there might simply be no role named 'admin'.
Reading CanCan's documentation on Role Based Authorization should shed some light on this subject.
精彩评论