【发布时间】:2015-05-29 18:59:21
【问题描述】:
我正在尝试构建一个调查表单,以便用户可以选择一个调查模板,然后将呈现一个包含特定于该模板的问题的表单。
class Survey < ActiveRecord::Base
belongs_to :template
belongs_to :patient
has_many :questions, :through=> :template
has_many :answers, :through=> :questions
end
class Template < ActiveRecord::Base
has_many :surveys
has_many :questions
end
class Question < ActiveRecord::Base
belongs_to :template
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
belongs_to :survey
end
问题表有一个包含 30 个预置问题的列表,每个模板都有:
create_table "questions", force: :cascade do |t|
t.integer "template_id"
t.text "content"
t.string "field_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "category"
t.string "options"
t.boolean "additional"
end
acl = Template.create(name:"ACL", body_part:"knee")
acl.questions.create(content:"Diagnosis", field_type:"text_area", category: "S")
我可以调用 Patient.surveys 来获取与患者相关的所有调查的列表。我可以致电 Patient.surveys.first.questions 以获取与给定调查相关的问题列表。
但我的困境是我无法弄清楚如何获得与特定调查的特定问题相关的答案。因为按照现在的设置,每个问题都有来自许多不同调查的多个答案。
理想情况下,我可以致电 Patient.surveys.first.questions.first.answer 以获得该问题的具体答案该调查。
但是现在,我需要像 Patient.surveys.first.questions.first.answers.where(survey_id: Survey.first.id)
所以我的问题是:
我需要在我的关联中进行什么调整以便我可以调用:
Patient.surveys.first.questions.first.answer 以获得与问题和调查相关的正确答案?
【问题讨论】:
标签: ruby-on-rails activerecord associations