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
是的,這是有道理的。非常感謝!! – Ning 2011-06-06 16:08:15
但是例如,Group#members()應該返回此組的所有成員。有沒有更簡單的方法來做到這一點?我想使用named_scope搜索3個表(用戶,組和USERGROUPROLE),有沒有更好的方法? – Ning 2011-06-06 16:15:34
@寧:從USERGROUPROLE where roleid =?select distinct userid。 [具有給定角色的所有用戶]從usergrouprole中選擇userid,roleid,其中groupid =? [所有用戶,按角色,在給定組中]。從usergrouprole中選擇不同的用戶標識,其中groupid =? [給定組中的所有用戶]您可能需要向表中添加其他索引以獲得良好的響應時間。 – Tim 2011-06-06 16:48:24