【问题标题】:Proper Setup of Active Record Associations for a Doctor-Patient Survey Model为医患调查模型正确设置活动记录关联
【发布时间】:2015-05-29 16:35:17
【问题描述】:

我在为医生 -> 患者关系建立 Active Record 关联时遇到了一些问题。

医生可以为他们的患者创建评估。但在他们创建评估之前,他们必须选择一个模板(针对伤害类型)。一个模板 has_many :questions 和一个 Question has_many :answers。

因此模型是:用户、患者、评估、模板、问题、答案。

用户 --> 患者关系非常简单,但我在模板、评估、问题和答案方面遇到了问题。我对'has_many:through'感到很困惑。我希望能够调用 Template.questions 来获取给定模板的问题列表,但能够调用 Assessment.questions(而不是 Assessment.template.questions)。 p>

然后我可以筛选 Assessment.questions 以获得答案。

这是我目前的模特协会。当前设置不允许我调用 Assessment.questions(我认为这将由 has_many :questions, :through=> :templates 处理)。

我需要更改哪些内容才能调用 Assessment.questions ?还接受有关架构的任何其他反馈。

谢谢

class User < ActiveRecord::Base
  has_many :patients
  has_many :assessments, dependent: :destroy
end

class Patient < ActiveRecord::Base
    belongs_to :user
    has_many :assessments, dependent: :destroy
end

class Assessment < ActiveRecord::Base
  belongs_to :user
  belongs_to :template
  belongs_to :patient
  has_many :questions, :through=> :templates
  has_many :answers, :through=> :questions
  accepts_nested_attributes_for :answers
end

class Template < ActiveRecord::Base
    belongs_to :assessment
    has_many :questions
end

class Question < ActiveRecord::Base
  belongs_to :template
  has_many :answers
end

class Answer < ActiveRecord::Base
  belongs_to :question
end

【问题讨论】:

  • 你有 belongs_to :assessment on template 和 belongs_to :template on 评估。这是个问题。
  • 患者通过评估有很多用户,用户通过评估有很多患者听起来是对的。您没有连贯地解释项目的目标或领域,让我很好地理解模型应该如何相互关联。
  • 谢谢@Noah。这是医生管理患者名单和进行评估的简单工具。我的目标是向所有患者展示,并且患者可以进行多项评估,这些评估都显示在他们的个人资料中。尽管患者在没有评估的情况下仍然可以存在
  • 无论如何,即使是你在 double belongs_to 上的第一点也解决了我的问题。现在我可以致电 Assessment.questions,谢谢!
  • 将 Patient 和 Users 更改为 has_many 有什么意义:与当前设置相比?

标签: ruby-on-rails activerecord associations


【解决方案1】:

就我个人而言,我会这样做。我可能不完全理解你的目标,但我想我明白了:

class Doctor < ActiveRecord::Base
    has_many :assessments
    has_many :patients, :through => :assessments
end

class Patient < ActiveRecord::Base
    has_many :assessments
    has_many :doctors, :through => :assessments
end

class Assessment < ActiveRecord::Base
    has_many :templates
    belongs_to :patient
    belongs_to :doctor
end

class Template < ActiveRecord::Base
    has_many :questions
    belongs_to :assessment
end

class Question < ActiveRecord::Base
    has_many :answers
    belongs_to :template
end

class Answer < ActiveRecord::Base
    belongs_to :question
end

【讨论】:

  • 我将如何呈现给定患者的评估列表?我最初想打电话给@patient.assessments 来查看历史
  • 经过我的编辑,你可以做 Patient.first.assessments。
  • 我的两个担忧:#1 我无法调用 Assessment.questions 来获得与该评估相关的问题的直接列表,#2 理想情况下,我想调用 Assessment.questions.first.answer获得该问题的相关答案相关评估
  • 明确地说,我有一个“问题”表,其中包含我正在为不同模板重复使用的问题列表。因此,并不是每次有新的评估时都会创建一个新的问题 ID。这是同一个 question_id,但在不同的assessment_id 上
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
相关资源
最近更新 更多