# encoding: utf-8 class Survey include Mongoid::Document include Mongoid::Timestamps ResultChart = 0 ResultExtern = 1 ResultFile = 2 scope :available_for_lang, ->(locale){ where("available_for_#{locale}".to_sym => true) } scope :can_display, where(is_hidden: false) field :title, :localize => true field :description, :localize => true field :create_user_id field :update_user_id field :postdate, :type => DateTime field :deadline, :type => DateTime field :is_hidden, :type => Boolean, :default => false field :result_type, :type => Integer, :default => 0 field :extern_link mount_uploader :upload_file, AssetUploader field :jump_mode, :type => Boolean, :default => false field :redirect_mode, :type => Boolean, :default => false field :redirect_url, :type => String validates :title, :at_least_one => true has_many :survey_questions, :autosave => true, :dependent => :destroy has_many :survey_answers, :dependent => :destroy accepts_nested_attributes_for :survey_questions, :allow_destroy => true before_save :check_deadline, :update_avliable_language def time_range r = "#{self.postdate.to_date}" r += "- #{self.deadline.to_date}" if self.deadline r end def result I18n.t 'survey.view_result' end def generate_chart_data survey_questions = self.survey_questions.all survey_answers = self.survey_answers.all chart_data = {} survey_questions.each do |question| qid = question.id.to_s case question.type when ::SurveyQuestion::Radio, ::SurveyQuestion::Select chart_data[qid] = {} answers = survey_answers.each do |answer| if answer[qid] chart_data[qid][answer[qid]] ||= 0 chart_data[qid][answer[qid]] += 1 end end when ::SurveyQuestion::Check chart_data[qid] = {} answers = survey_answers.each do |answer| if answer[qid] answer[qid].each do |option| chart_data[qid][option] ||= 0 chart_data[qid][option] += 1 end end end when ::SurveyQuestion::Radiogroup chart_data[qid] = {} answers = survey_answers.each do |answer| if answer[qid] answer[qid].each do |option, group| chart_data[qid][option] ||= {} chart_data[qid][option][group] ||= 0 chart_data[qid][option][group] += 1 end end end end end [chart_data, survey_questions, survey_answers] end protected def check_deadline if(!self.deadline.nil? and (self.deadline < self.postdate )) self.deadline = nil end end def update_avliable_language VALID_LOCALES.each do |locale| if (title_translations[locale].blank? rescue true) self["available_for_#{locale}".to_sym] = false else self["available_for_#{locale}".to_sym] = true end end end end