问题描述
我们假设你的应用有两个独立的设计师用户模型称为用户
和 Admin
。这意味着您可以并行使用 current_user
和 current_admin
之类的方法。
我们进一步假设你只需要/想要一个能力
类,其中包含所有CanCan权限设置...
class Ability
include CanCan :: Ability
def initialize(user)
用户|| = User.new
用户
当用户
可以:创建,注释
可以:读取:全部
当Admin
可以:管理,:全部
结束
结束
结束
这是正是其他人提出的,但还有一个步骤你必须采取。
默认情况下,CanCan假定方法 current_user
存在并返回一个User对象,以便与您的能力
设置进行比较。但是,我们的管理员用户可以使用 current_admin
找到。没有告诉CanCan在哪里找到管理对象,他们从来没有得到审查,从而没有获得权限; 我们必须在处理管理员时更改默认值。
将以下内容添加到 application_controller.rb
...
def current_ability
如果admin_signed_in?
@current_ability || = Ability.new(current_admin)
else
@current_ability || = Ability.new(current_user)
end
end
现在,我们的能力类将会看到Admin对象(如果有的话)可用,并且在不存在时退回到普通用户
进一步的开发允许我们将管理员权限移动到自己的独立能力类中...
def current_ability
如果admin_signed_in?
@current_ability || = AdminPowers.new(current_admin)
else
@current_ability || = Ability.new(current_user)
end
end
有关详细信息,请参阅。赞许指出我正确的文章。
FYI - CanCan已死亡,长时间 !最新的bug修复和新功能。相同的命名空间,所以它只是一个宝石替代您的宝石文件。
gem'cancancan','〜> 1.8'
How would I go about defining abilities for several devise models?
Let's assume your app has two separate Devise-powered user models called User
and Admin
. This means you use methods like current_user
and current_admin
side by side.
Let's further assume that you only have/want a single Ability
class, which contains all your CanCan permission settings...
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
case user
when User
can :create, Comment
can :read, :all
when Admin
can :manage, :all
end
end
end
This is exactly what others have proposed, but there's another step you have to take.
By default, CanCan assumes that the method current_user
exists and will return a User object to compare with your Ability
settings. However, our admin users can be found using current_admin
. Without telling CanCan where to find admin objects, they never get reviewed, and thus never get permissions; we must change the defaults when dealing with an admin.
Add the following to application_controller.rb
...
def current_ability
if admin_signed_in?
@current_ability ||= Ability.new(current_admin)
else
@current_ability ||= Ability.new(current_user)
end
end
Now our Ability class will look at the Admin object if one is available, and fall back on a normal User when none is present.
Further development allows us to move Admin permissions into their own separate Ability class...
def current_ability
if admin_signed_in?
@current_ability ||= AdminPowers.new(current_admin)
else
@current_ability ||= Ability.new(current_user)
end
end
For more info, see Changing Defaults in the Wiki. Kudos to Stefan for pointing me at the proper article.
FYI -- CanCan is dead, long live CanCanCan! Up to date with bug fixes and new features. Same namespaces, so it's just a drop-in gem replacement in your Gemfile.
gem 'cancancan', '~> 1.8'
这篇关于CanCan如何集成多种设计模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!