Sha256: 4c93ebbbb8524d1382a1312c93dd4d91babe2d8eaa6f81a425494839f69d2b55

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

module Tasks
  module Taskables
    class Question::Answer < ActiveRecord::Base
      include Taskable::Submission

      belongs_to :author, polymorphic: true
      has_many :votes, dependent: :destroy

      validates :author_id, :author_type, presence: true
      validates :votes, length: { minimum: 1 }
      validate :can_only_answer_each_question_once
      validate :can_only_vote_once_for_single_choice_questions

      def question
        if votes.any?
          votes.first.option.question
        else
          raise StandardError, "Cannot derive question for #{self}, as it has no votes"
        end
      end

      request is: :question

      def correct?
        votes.all? { |vote| vote.option.correct? }
      end

      private

      def can_only_answer_each_question_once
        errors.add :base, I18n.t('tasks.taskables.questions.answers.already_answered') if question.answers.find_by author: author
      end

      def can_only_vote_once_for_single_choice_questions
        errors.add :base, I18n.t('tasks.taskables.questions.answers.can_only_vote_once') if question.single? && votes.many?
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tasuku-0.0.1 app/models/tasks/taskables/question/answer.rb