【发布时间】: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