2010-05-10 64 views
0

habtm協會通常需要三種(或更多)方式關聯。例如一個包含角色的權限模型。有沒有辦法在rails/activerecord中有三種方式的habtm關聯?

功能的特定區域有許多用戶可以訪問許多區域。

上的所述區域的權限是通過角色(HABTM)設置

用戶/角色關聯也HABTM

的權限(讀,寫,刪除等)是朝向角色的habtm。

用rails/activerecord怎麼做最好?

+0

我不完全相信你是問這裏。可能值得添加一些關於如何訪問數據的示例代碼。假設你所要求的是可能的,舉一個你如何使用它的例子。 – Will 2010-05-10 19:02:58

回答

2

我不確定您是否僅使用基於角色的用戶權限作爲示例,或者如果這實際上是您的目標。

嵌套habtm關係很容易在Rails的,雖然我會強烈建議嵌套has_many :through,剛剛成立起來,你會想象:

class Permission < ActiveRecord::Base 
end 

#this table must have permission_id and role_id 
class PermissionAssignment < ActiveRecord::Base 
    belongs_to :permission 
    belongs_to :role 
end 

class Role < ActiveRecord::Base 
    has_many :users, :through => :role_assignments 
    has_many :permissions, :through => :permission_assignments 
end 

#this table must have user_id and role_id  
class RoleAssignment < ActiveRecord::Base 
    belongs_to :role 
    belongs_to :user 
end 

class User < ActiveRecord::Base 
    has_many :roles, :through => :role_assignments 
end 
相關問題