[英]Constructing queries for collecting survey data from my survey database design
我有一個相對簡單的模型設計,用於創建調查,將調查分配給用戶以及由這些用戶填寫調查。 一切正常,但是在從那些調查中檢索數據時,我處在不確定哪種方法正確,尤其是哪種方法正確的狀態。
我的模型設計如下:(為清楚起見,僅保留了相關代碼)
class Survey < ActiveRecord::Base
has_many :survey_sections, dependent: :destroy
has_many :survey_assignments
has_many :participants , :through => :survey_assignments, :source => :user
has_many :survey_responses
end
class SurveySection < ActiveRecord::Base
belongs_to :survey
has_many :survey_questions, dependent: :destroy
has_many :survey_options, dependent: :destroy
end
因此,調查分為許多部分,每個部分都有很多問題,每個部分都有很多選項,選項基本上是當前部分中所有問題的預定義答案。 這是設計決定,因此我不需要每個問題都有很多選擇...
class SurveyQuestion < ActiveRecord::Base
belongs_to :survey_section
has_many :survey_answers
end
class SurveyAnswer < ActiveRecord::Base
belongs_to :survey_option
belongs_to :survey_question
belongs_to :survey_response
end
class SurveyOption < ActiveRecord::Base
#it has 2 fields 'weight'(int) and 'text'(string)
belongs_to :survey_section
end
醫生可以為患者分配調查並指定日期,直到他們可以進行調查為止。
class SurveyAssignment < ActiveRecord::Base
#has also a field valid_until(date)
belongs_to :user
belongs_to :survey
has_many :survey_responses
end
我也在記錄調查答復。 因此,每次用戶填寫表單時,都會在survey_responses表中創建一個新記錄。 由於調度的實現,我稍后將需要它,在此用戶可能已分配調查,他應該[在此處輸入一些數字] X [天|周|月]。
class SurveyResponse < ActiveRecord::Base
belongs_to :survey_assignment
belongs_to :survey
belongs_to :user
has_many :survey_answers
end
現在,我需要顯示調查結果圖。 就像您在代碼中看到的那樣,結果是整數(請參閱SurveyOption類),我需要為特定用戶進行的特定調查加起來。 假設我有一個user_id和survey_id,現在我想檢索所有這些用戶的調查答復,但是對於每個調查答復,我需要他們的答案具有的權重之和(SurveyOption)。
如果執行以下查詢,我將獲得他所有回答的答案總和:
SurveyResponse.joins(:survey_answers => :survey_option).where(user_id: 96, survey_id:63).select("survey_option.weight").sum("weight")
但我想得到該用戶對該陣列的調查的每一個答復,像這樣
[[survey_response.created_at.to_i, the_sum_of_weights],[...],[...],....]
那么做這樣的最好的方法是什么? 如果我認為純粹是在sql statemets中,我認為可以在單個查詢中完成,是否可以在單個查詢中完成。
如果有人需要我進一步闡述,我們可以在評論中進行討論。 謝謝你的協助。
我猜我想要產生的sql語句是:
SELECT survey_responses.id, survey_responses.created_at, SUM (survey_options.weight) FROM "survey_responses" INNER JOIN "survey_answers" ON "survey_answers"."survey_response_id" = "survey_responses"."id" INNER JOIN "survey_options" ON "survey_options"."id" = "survey_answers"."survey_option_id" WHERE "survey_responses"."user_id" = 96 AND "survey_responses"."survey_id" = 64 GROUP BY survey_responses.id, survey_responses.created_at;
我想我快要解決自己的問題了:)))
因此,經過一番研究,我找到了一種方法。
result = SurveyResponse.joins(:survey_answers => :survey_option).where(user_id: 96, survey_id: 64).select("SUM (survey_options.weight) as score, survey_responses.created_at").group("survey_responses.created_at, survey_responses.id")
然后我可以在ActiveRecord :: Relation對象上使用find_each函數。
result.find_each do |r|
puts " score: #{r.score} created_at: #{r.created_at}"
end
find_each比每個都更好,因為它一次加載了1000條記錄,因此不會浪費您的內存。 想象一下加載數百萬條記錄。
如果有人有更好的查詢解決方案,請分享,我會接受的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.