多对多设计,同一对象上的两种关系?

时间:2011-06-06 13:58:28

标签: ruby-on-rails-3 many-to-many

例如,一个用户已加入多个组,一个组有许多用户成员。这是一种正常的多对多关系。但是,我想将用户识别为“成员”和“所有者”:一组将拥有许多“所有者”和许多“成员”;每个用户可以是所有者或组成员。同时,“所有者”也应该是一种“成员”。我该如何创建这样的表结构?

我有这样的正常多对多关系,在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 个答案:

答案 0 :(得分:1)

您需要以下表格:

           USERS
           GROUPS
           ROLES
           USERGROUPROLE

USERGROUPROLE表是这样的:

         userid  references USER
         groupid references GROUPS
         roleid  referencees ROLES

         Primary key (userid, groupid, roleid)

这将允许组的所有者也是该组的成员。它将允许该组拥有多个所有者和多个成员。一个小组有0个或更多成员;一个群体有0个或更多的所有者。

您可以拥有一个PERMISSIONS和一个ROLEPERMISSIONS表来识别特定角色的权力。 ROLE具有0或更多权限。

          ROLEPERSMISSIONS
          roleid references ROLES
          permissionid references PERMISSIONS

示例权限:

         can delete
         can edit
         can create new topic
         can attach file