令人困惑的ActiveRecord关系 - Ruby on Rails

时间:2013-08-17 18:15:49

标签: ruby-on-rails activerecord

我正在努力为医生和他们的培训计划/专业设计关系。示例如下:

  • 一个项目有一个专业/项目(例如大学神经病学培训项目,专门研究神经病学)
  • 医生可以有多个项目,因此有多个专业(例如,史密斯博士是参加大学神经病学培训项目的神经病学家,而琼斯博士是参加大学神经病学培训项目和大医院儿科项目的神经病学家和儿科医生)

它似乎可以设置为has_many:through ...但是,当我尝试将其概念化时,这似乎不高效或正确。我有另一个很大程度上不相关的模型,它与专业(但不是程序)联系在一起,这就是为什么我不把程序和专业结合起来。我应该能够访问User.programs.all和Program.users.all:

模型用户:

has_many程序

has_many特色,:通过=> :程序

模型程序:

belongs_to:user

belongs_to:专业

模特专长:

has_many:users,:through => :程序

has_many:程序

2 个答案:

答案 0 :(得分:2)

你可以拥有类似下面的模型。

class Doctor
  has_many :specialties, :through => :practices
  has_many : enrollments
  has_many :programs , :through => : enrollments  
end

class Program
  has_many : enrollments
  has_many :doctors, :through => : enrollments
  belongs_to :specialty  
end

class Enrollment
  belongs_to : doctor
  belongs_to :program 
end

class Specialty
  has_many :practices
  has_many :doctors, :through => :practices   
  has_many :programs  
end

class Practice
  belongs_to :doctor
  belongs_to :specialty 
end

希望它有所帮助。

<强>更新 如果医生只能通过程序获得专业,那么就可以这样建模。

class Doctor
  has_many :enrollments
  has_many :programs, :through => :enrollments
end

class Program
  has_many :enrollments
  has_many :doctors, :through => :enrollments
  belongs_to :specialty  
end

class Enrollment
  belongs_to :doctor
  belongs_to :program 
end

class Specialty
  has_many :programs
  has_many :enrollments , :through => :programs
end

获得所有专科医生,例如神经病学。

@neurology.enrollments.collect { |c| c.doctor }.uniq

或者

 Doctor.includes(:enrollments).where(:enrollments => {:specialty_id => @neurology.id})

要获得医生的所有专业,你必须这样做。

 @doctor.programs.collect { |p| p.specialty }.uniq

答案 1 :(得分:0)

不要通过程序链接到专业。

使专业和课程独立。

您似乎很有可能遇到医生专业但没有参加任何有意义的“计划”的情况。

您可以添加从专业到程序的“软”链接:在模型专业中添加“belongs_to:program”,程序可能为NULL。