我正在尝试构建一个调查表单,这样用户就可以选择一个survey模板,然后就会呈现一个带有特定于该模板的问题的表单。
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要得到与问题和调查都相关的正确答案吗?
发布于 2015-05-29 19:15:26
首先要注意的是,您正在执行多个查询,实际上可以弹出一个过程范围。我不知道什么是对你的需求的大局,所以我可以完全不想知道什么对你来说更重要。
要具体地回答你的问题,你可以定义一个方法来抓住正确的答案。
def answer
survey=Survey.joins(:templates).where(:templates {id: self.template_id, question_id: self.id}).first
Answer.where(:survey_id => survey.id).first
end那就叫它吧
patient.surveys.first.questions.first.answer
您也可以通过将其弹出到您的答案模型中来直接进行范围界定以获得您的答案。
scope :for_survey_question, lambda {|survey, question| where(:survey_id => survey.id, :question_id => question.id).first }并将其称为Answer.for_survey_question(调查表、问题)(其中调查和问题都是调查对象和问题模型对象,分别作为参数加载和传递)
https://stackoverflow.com/questions/30537132
复制相似问题