如果您的用戶角色的東西正在尋找類似以下內容:
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
或者,您可以刪除您的用戶角色has-many-through關聯並將其替換爲easy-roles gem - 非常有用。它可以在github上獲得:https://github.com/platform45/easy_roles
現在你應該知道如何使用cancan,角色和所有的東西一起工作:-)。
http://railscasts.com/episodes/192-authorization-with-cancan嘗試觀看本教程 – Pierre
在能夠提供任何有用答案之前,我們確實需要了解更多關於您嘗試的內容去做。也許從描述「用戶」和「角色」模型開始,以及它們如何與您試圖驗證的其他模型進行交互。 – Jon