组与用户的直接关联

时间:2012-03-01 08:46:51

标签: mysql ruby-on-rails ruby ruby-on-rails-3 associations

我有集体模式,有很多机构和学校。

class Group
  has_many :institutions
  has_many :schools
end

但是我需要我的小组来拥有_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

显然这是不可能的,所以我该怎么办?

1 个答案:

答案 0 :(得分:1)

只是随便,您是否考虑使用单表继承,以便学校是一种机构?

您的学校课程将继承自学院(“Class School< Institution”)。另外,我猜你也称之为别的,但你也可以拥有“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

您可能需要指定一两个外键才能让它适合您。

另外,我无法想象看什么:INSTIT_education是什么,但如果你真的需要它,你可以在那里做同样的事情(也许是“class institutional_education< education”,或者反过来。