【问题标题】:Confusing ActiveRecord relationship - Ruby on Rails令人困惑的 ActiveRecord 关系 - Ruby on Rails
【发布时间】:2013-08-17 18:15:48
【问题描述】:

我正在尝试为医生及其培训计划/专业设计关系。示例如下:

  • 一个课程有一个专业/课程(例如,大学神经病学培训课程专门研究神经病学)
  • 医生可以拥有多个课程,因此可以拥有多个专业(例如,Smith 博士是参加大学神经病学培训课程的神经科医生,而 Jones 博士是参加大学神经病学培训课程和大医院儿科课程的神经科医生和儿科医生)

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

模型用户:

有_许多程序

has_many 专业,:through => :programs

示范项目:

belongs_to :user

belongs_to :specialty

模特专长:

has_many :users, :through => :program

has_many :程序

【问题讨论】:

  • 一个程序是否只属于一个用户?或者一个程序也可以有很多医生?
  • 一个程序有很多医生。
  • 我认为,您将需要 5 个模型。我会添加一个答案。
  • 是的,正如@squadette 所提到的,你们很多人不想通过程序链接专业。我已经在答案中解决了这个问题。

标签: ruby-on-rails activerecord


【解决方案1】:

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

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

【讨论】:

  • 谢谢。问题既然医生专业总是和程序的专业一样,是否可以改成:Doctor has_many: specialties,:through program?
  • 好的。我现在明白了。您的意思是,只有参加过该计划的医生才能成为专家。顺便说一句,您确定他可能不想两次参加同一个专业课程吗? :) 在不同的地方可能是? :)
  • 对!所以通过参加一个项目,他们成为了那个专业。您只能在一个课程中为某个专业培训一次。从表面上看,在专业项目中只写一个专栏是有道理的,但由于外部模型,我不能这样做。
  • "在程序中只为专业设置一列是有意义的,但是由于外部模型,我不能这样做"您的意思是程序不能将specialty_id作为列吗?
  • 技术上可以,但我有一个单独的模型,需要与专业相关联并且与程序无关......所以它没有意义。
【解决方案2】:

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

使专业和程序独立。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多