2014-02-17 20 views
0

我在努力尋找最簡單的解決方案,三種型號關聯:右鍵關聯模型之間有三個

  1. 用戶
  2. 組織
  3. 角色

用戶和組織是一個HABTM協會 - 一個用戶可以有多個組織,反之亦然。

一個用戶也可以有多個角色,但每個組織只有一個角色。

現在我有這個在我的模型:

user.rb

class User < ActiveRecord::Base 
    has_many :roles, through: :organizations 
    has_and_belongs_to_many :organizations, :join_table => :organizations_users 
end 

organization.rb

class Organization < ActiveRecord::Base 
    has_and_belongs_to_many :users, :join_table => :organizations_users 
    has_many :roles 
end 

role.rb

class Role < ActiveRecord::Base 
    has_many :users, through: :organizations 
    belongs_to :organizations 
end 

這有道理嗎?

回答

1

這裏是我的思想:

  • 假設你正在使用的has_and_belongs_to_many並給予Rails的默認值,你的join_table的規格是多餘的
  • has_many :roles, through: :organizations如果你同時擁有role只會工作以及organizations表中的user字段,因爲Rails希望執行該表的SQL select以查找這些字段。

既然你希望用戶有每個組織長達一個一個角色,那麼我想最簡單的事情將是一個role字段添加到organizations_users模型,如下:

用戶。 RB

class User < ActiveRecord::Base 
    has_many :roles, through: :organizations_users 
    has_many :organizations, :through => :organizations_users 
    has_many :organizations_users 
end 

organization.rb

class Organization < ActiveRecord::Base 
    has_many :users, :through => :organizations_users 
    has_many :roles, :through => :organizations_users 
    has_many :organizations_users 
end 

organization_user.rb

class OrganizationUser < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :organization 
    belongs_to :role 
end 

role.rb

class Role < ActiveRecord::Base 
end 

上述假設你有一些理由要Role繼續成爲一個ActiveModel,而不是隻是一個organizations_users表中的字符串字段。

+0

完美,這就像一個魅力!只有一個問題 - 當我使用種子數據填充數據庫時,現在有4個colums(id,user_id,organization_id,role_id)的organizations_users表爲每個關聯創建單獨的條目,例如_user 1 - 組織1_和_user 1 - 角色1_而不是_user 1 - 組織1 - 角色1_。任何建議我怎麼能解決這個問題? –

+0

你如何創建條目?如果您通過'has_many'輔助方法_other_而不是'organizational_users'的輔助方法進行分配,那麼會發生這種情況,因爲其他輔助方法只知道兩個元素之間的關聯。 –

+0

這是有道理的...現在我正嘗試在控制檯中使用此代碼創建一個新用戶:'OrganizationUserRole#create_user(email:'[email protected]',password:'password')'(而不是用戶OrganizationUser我現在使用模型OrganizationUserRole。應該選擇更短的東西...無論如何)。結果是'=> OrganizationUserRole(id:integer,user_id:integer,organization_id:integer,role_id:integer)' - 我仍然在做錯事,但我不知道什麼 –

相關問題