class SurveyAnswer include Mongoid::Document include Mongoid::Timestamps include Mongoid::Attributes::Dynamic field :user, type: BSON::ObjectId field :consent_used, type: Boolean, :default => false field :scored_points, type: Integer, :default => 0 field :avg_points, type: Integer field :individual_total, type: Array, :default => [] field :select_question, type: Array, :default => [] field :color, type: String belongs_to :questionnaire_survey after_create do if self.questionnaire_survey info = {:questionnaire_survey_id=>self.questionnaire_survey.id,:user=>self.user} if self.user.blank? info[:survey_answer_ids] = [self.id] end answer_group = SurveyAnswerGroup.where(info).first if answer_group.nil? answer_group = SurveyAnswerGroup.new(info) end answer_group.last_modified = self.created_at answer_group.survey_answer_ids << self.id answer_group.save end end after_save do answer_group = SurveyAnswerGroup.where(:questionnaire_survey_id=>self.questionnaire_survey.id,:user=>user).first if answer_group answer_group.last_modified = self.created_at answer_group.save end end before_destroy do answer_group = SurveyAnswerGroup.where(:user=>self.user,:questionnaire_survey_id=>self.questionnaire_survey_id).first if answer_group answer_group.survey_answer_ids.delete(self.id) if answer_group.survey_answer_ids.count == 0 answer_group.destroy else answer_group.save end end end def get_avg_points if self.avg_points.nil? total_weight = self.questionnaire_survey.get_total_weight(self) self.avg_points = (scored_points.to_f / total_weight).round self.save self.avg_points else self.avg_points end end end