2011-06-06 76 views
0

例如,一個用戶已加入許多組,一個組有許多用戶成員。這是一個正常的多對多關係。但是,我想將用戶識別爲「成員」和「所有者」:一個組將擁有許多「所有者」和許多「成員」;每個用戶可以是所有者或組的成員。同時,「所有者」也應該是一種「成員」。我應該如何創建這樣的表結構?多對多設計,2種關於同一物體的關係?

我有這樣的正常的多對多關係,還有一個字段在:group_user_relations表中標識用戶是成員還是所有者。

class User < ActiveRecord::Base 
    # many-to-many to groups 
    has_many :group_user_relations 
    has_many :groups, :through => :group_user_relations 
end 


class Group < ActiveRecord::Base 
    # many-to-many to users 
    has_many :group_user_relations 
    has_many :users, :through => :group_user_relations 
    alias_attribute :members, :users 
end 

回答

1

您需要以下表格:

  USERS 
      GROUPS 
      ROLES 
      USERGROUPROLE 

的USERGROUPROLE表是這樣的:

  userid references USER 
     groupid references GROUPS 
     roleid referencees ROLES 

     Primary key (userid, groupid, roleid) 

這將允許一組的所有者是也是該集團的一員。這將允許該組擁有多個所有者和多個成員。一個組有0個或更多成員;一個組有0個或更多的所有者。

您可以通過PERMISSIONS和ROLEPERMISSIONS表來識別特定角色的權限。角色擁有0個或更多權限。

  ROLEPERSMISSIONS 
      roleid references ROLES 
      permissionid references PERMISSIONS 

樣品權限:

  can delete 
     can edit 
     can create new topic 
     can attach file 
+0

是的,這是有道理的。非常感謝!! – Ning 2011-06-06 16:08:15

+0

但是例如,Group#members()應該返回此組的所有成員。有沒有更簡單的方法來做到這一點?我想使用named_scope搜索3個表(用戶,組和USERGROUPROLE),有沒有更好的方法? – Ning 2011-06-06 16:15:34

+1

@寧:從USERGROUPROLE where roleid =?select distinct userid。 [具有給定角色的所有用戶]從usergrouprole中選擇userid,roleid,其中groupid =? [所有用戶,按角色,在給定組中]。從usergrouprole中選擇不同的用戶標識,其中groupid =? [給定組中的所有用戶]您可能需要向表中添加其他索引以獲得良好的響應時間。 – Tim 2011-06-06 16:48:24