ruby on rails - ActiveRecord Survey Model ActiveRecord Associations for Doctor -> Patient -
i'm trying build survey form user can select survey template, , form rendered questions specific template.
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
the questions table has list of 30 pre-seeded questions go each template:
create_table "questions", force: :cascade |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")
i can call patient.surveys list of surveys associated patient. can call patient.surveys.first.questions list of questions associated given survey.
but dilemma can't figure out how answer associated specific question specific survey. because it's setup now, each question has multiple answers many different surveys.
ideally able call patient.surveys.first.questions.first.answer specific answer question for survey.
but now, need go patient.surveys.first.questions.first.answers.where(survey_id: survey.first.id)
so question is:
what need adjust in associations can call:
patient.surveys.first.questions.first.answer correct answer associated both question , survey ?
well, first thing note performing multiple queries can pop 1 procedural scope. have no idea big picture needs totally off more important you.
to answer question specifically, can define method in question grabs right answer.
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
then call
patient.surveys.first.questions.first.answer
you can scoping answer directly popping answer model
scope :for_survey_question, lambda {|survey, question| where(:survey_id => survey.id, :question_id => question.id).first }
and calling anywhere answer.for_survey_question(survey,question) (where survey , question both survey , question model objects loaded , passed in parameters respectively)
Comments
Post a Comment