我正试图为一名医生和他们的培训项目/专业设计关系。例子如下:
它似乎可以设置为一个has_many :通过.然而,当我试图将它概念化时,这似乎是不有效或不正确的。我有另一个基本上不相关的模型,它与专业(但不是程序)联系在一起,这就是为什么我不把项目和专业结合起来的原因。我应该能够访问User.programs.all和Program.users.all:
模型用户:
has_many程序
has_many专业,通过=>:程序
示范方案:
belongs_to :用户
belongs_to :特产
示范专业:
has_many :用户,:通过=>:程序
has_many :程序
发布于 2013-08-17 18:42:48
你可以有下面这样的模型。
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发布于 2013-08-17 18:34:19
不要通过程序链接到专业。
使其专业和程序是独立的。
似乎你有很好的机会遇到一个病例,医生有一个专业,但没有参加任何有意义的“项目”。
您可以添加从专业到程序的“软”链接:在模型专业中添加"belongs_to : program ",程序可能为NULL。
https://stackoverflow.com/questions/18291923
复制相似问题