2013-05-27 33 views
1

我正在試圖找到一種解決方案,但並非所有這些都對我顯而易見。一個非常擅長這個東西的朋友給了我他的看法,但是我想知道是否有軌道模式 - 我缺少的知識是軌道如何創建關係...如何在Rails中加入多角色,多組織表格

我有一個類似問題的空間這個。用戶可以在多個組織中執行多個角色。因此,例如,用戶可以是組織1中的「標準用戶」和「高級用戶」,但是組織2中的「管理員」。

我正在使用Devise和CanCan。我有一個Users表,Roles和一個Organizations表以及一個roles_users表來管理這個多對多的關係。然後我有一個user_organisations表,用於存儲用戶和組織之間的M2M。這一切工作正常。當我這樣做時;

user = User.new({ :email => '[email protected]', 
:password => 'password', 
:password_confirmation => 'password', 
:firstname => 'TestFirstName', 
:surname => 'TestSurName'}) 

org1 = Org.new({:fullname => 'Test Org 1'}) 
org1.save 

org2 = Org.new({:fullname => 'Test Org 2'}) 
org2.save 

user.org << Org.first 
user.org << Org.last 

user.roles << Role.where('name'=>'administrator').first 
user.roles << Role.where('name'=>'PowerUser').first 

我得到了(如您所料)兩個組織和一個用戶在兩個組織中註冊。

缺失的位是角色。我有一個新的模型(通過賦值使用),roles_user_orgs(這意味着作爲user_org表與角色之間的鏈接),並通過使用user_org的主鍵和角色id來存儲用戶的角色。但它從來沒有人口稠密。我不知道是否這是因爲我沒有正確地寫入插入來填充它,或者因爲我的關係不正確 - 或者 - 因爲設計是錯誤的,並且在rails中不起作用。該模型傻笑是使用在user_roles表的org_id,但我不知道如何來填充這個......

這裏是我的組織...

class Role 

has_many :user_roles, :dependent => :destroy 
has_many :users, :through => :user_roles, :uniq => true 

has_many :role_user_orgs, :dependent => :destroy 
has_many :user_orgs, :through => :role_user_orgs 


class Org 
has_many :user_orgs 
has_many :users, :through => :user_orgs 

class UserOrg 
belongs_to :org 
belongs_to :user 

has_many :role_user_orgs, :dependent => :destroy 
has_many :roles, :through => :role_user_orgs 

class UserRole 
belongs_to :User 
belongs_to :role 

class User 
has_many :user_roles 
has_many :roles, :through => :user_roles 
has_many :user_orgs 
has_many :orgs, :through => :user_orgs 


class RoleUserOrg 
belongs_to :role 
belongs_to :user_orgs 

回答

5

我覺得你這裏的東西過於複雜。我看到它的方式,你需要一個名爲memberships一個表應作爲用戶,組織之間和角色連接錶行動

class Membership 
    belongs_to :user 
    belongs_to :org 
    belongs_to :role 


class User 
    has_many :memberships 
    has_many :orgs, through: :memberships 
    has_many :roles, through: :memberships 

組織內爲用戶創建一個新的角色,只是做:

org = Org.create({:fullname => 'Test Org 1'}) 
role = Role.where('name'=>'administrator').first 
membership = user.memberships.create(org_id: org.id, role_id: role.id) 

要查詢一個組織中的角色,你可以這樣做:

org = Org.where(name: "Test Org").first 
my_roles = Role.find(user.memberships.where(org_id: org.id).map(&:role_id)) 
+0

感謝米哈伊,我就來看看.... – MikeB

+0

米哈伊這是個好感謝,要簡單得多。只需要得到ActiveRecord的竅門 - 用兩個參數創建是顯而易見的現在我看到它.. – MikeB

+0

我有同樣類型的問題,你能幫助這裏:http://stackoverflow.com/questions/25985163/rails- ActiveRecord的 - 三表具有一對多的貫通協會 – Sauron