Sha256: b6cb38611cb9f5d6d0baf83adfbc952c26e7dae07e7fcea79793805de9922790

Contents?: true

Size: 1.18 KB

Versions: 6

Compression:

Stored size: 1.18 KB

Contents

# frozen_string_literal: true

module Decidim
  module Meetings
    # This command is executed when the user creates an Answer in a meeting poll.
    class CreateAnswer < Decidim::Command
      delegate :current_user, to: :form

      def initialize(form, questionnaire)
        @form = form
        @questionnaire = questionnaire
      end

      # Creates the answer if valid.
      #
      # Broadcasts :ok if successful, :invalid otherwise.
      def call
        return broadcast(:invalid) if form.invalid?

        transaction do
          answer_question
        end

        broadcast(:ok)
      end

      private

      attr_reader :form, :answer

      def invalid?
        form.invalid?
      end

      def answer_question
        answer = Answer.new(
          user: current_user,
          questionnaire: @questionnaire,
          question: form.question
        )

        form.selected_choices.each do |choice|
          answer.choices.build(
            body: choice.body || translated_attribute(AnswerOption.find_by(id: choice.answer_option_id)&.body),
            decidim_answer_option_id: choice.answer_option_id
          )
        end

        answer.save!
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
decidim-meetings-0.29.1 app/commands/decidim/meetings/create_answer.rb
decidim-meetings-0.29.0 app/commands/decidim/meetings/create_answer.rb
decidim-meetings-0.29.0.rc4 app/commands/decidim/meetings/create_answer.rb
decidim-meetings-0.29.0.rc3 app/commands/decidim/meetings/create_answer.rb
decidim-meetings-0.29.0.rc2 app/commands/decidim/meetings/create_answer.rb
decidim-meetings-0.29.0.rc1 app/commands/decidim/meetings/create_answer.rb