2012-03-01 61 views
2

我有has_many機構和學校的組模型。與用戶的組直接關聯

class Group 
    has_many :institutions 
    has_many :schools 
end 

不過,我需要我的集團have_and_belongs_to_many:用戶,但我想一切都是通過機構和學校這樣的關聯的用戶:

class Group 
    has_many :institutions 
    has_many :users, :through => :instiutions 
    has_many :schools 
    has_many :users, :through => :schools 
end 

class School 
    belongs_to :group  

    has_many :educations 
    has_many :users, :through => :educations 
end 

class Institution 
    belongs_to :group  

    has_many :institutional_educations 
    has_many :users, :through => :institutional_educations 
end 

顯然這是不可能的所以我應該怎麼做?

+0

如何定義您的院校和學校模式? – shingara 2012-03-01 08:51:05

回答

1

只是非正式的,你有沒有考慮過使用單表繼承,所以學校是一種機構?

你的學校班級將繼承學校(「班級學校<機構」)。另外,我想你會把它稱爲別的東西,但你也可以有「Class GenericInstitution < Institution」。然後您的Group類可能如下所示:

class Group 
    :has_many :school_users, :through => :schools, 
    :has_many :generic_institution_users, :through => :generic_institutions 

    # if you need all of the users at once: 
    :has_many :users, :through => :institutions 
end 

您可能必須指定一個外鍵或兩個外鍵才能使用它。

而且,我不是很圖中看到的東西:institutional_education是的,但如果你真的需要它,你可以做同樣的事情在那裏(也許「類institutional_education <教育」,也可能反過來