如果您的用户角色内容类似于以下内容:
class User < ActiveRecord::Base
has_many :user_roles
has_many :roles, :through => :user_roles
# user model has for example following attributes:
# username, email, password, ...
end
class Role < ActiveRecord::Base
has_many :user_roles
has_many :users, :through => :user_roles
# role model has for example following attributes:
# name (e.g. Role.first.name => "admin" or "editor" or "whatever"
end
class UserRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
您可以执行以下操作:
首先,使用一些辅助方法或类似方法扩展您的用户模型:
class User < ActiveRecord::Base
def is_admin?
is_type?("admin")
end
def is_editor?
is_type?("editor")
end
def is_whatever?
is_type?("whatever")
end
private
def is_type? type
self.roles.map(&:name).include?(type) ? true : false # will return true if the param type is included in the user´s role´s names.
end
end
第二,扩展你的能力等级:
class Ability
include CanCan::Ability
def initialize(user)
if user
can :manage, :all if user.is_admin?
can :create, Project if user.is_editor?
can :read, Project if user.is_whatever?
# .. and so on..
# you can work with your different roles on base of the given user instance.
end
end
end
或者,您可以删除您的 User-Roles has-many-through 关联并将其替换为 easy-roles gem - 非常有用。可以在 github 上找到:https://github.com/platform45/easy_roles
现在您应该知道如何将 cancan、角色和所有东西一起使用 :-)。