Files
grecia/app/models/poll/answer.rb
Javi Martín 24ccf23ed8 Don't save the answer if the voter is not recorded
Up until now, we were assuming the voter was valid, but were not raising
an exception if it wasn't. And in the user interface everything seemed
to be working properly.

We were having this issue when skipping verification, when there could
be voters without a document number, which would be considered invalid.

Raising an exception when failing to save the voter and making sure the
answer and the voter are saved inside a transaction solves the problem.
2020-08-07 11:52:24 +02:00

25 lines
842 B
Ruby

class Poll::Answer < ApplicationRecord
belongs_to :question, -> { with_hidden }, inverse_of: :answers
belongs_to :author, -> { with_hidden }, class_name: "User", inverse_of: :poll_answers
delegate :poll, :poll_id, to: :question
validates :question, presence: true
validates :author, presence: true
validates :answer, presence: true
validates :answer, inclusion: { in: ->(a) { a.question.possible_answers }},
unless: ->(a) { a.question.blank? }
scope :by_author, ->(author_id) { where(author_id: author_id) }
scope :by_question, ->(question_id) { where(question_id: question_id) }
def save_and_record_voter_participation(token)
transaction do
touch if persisted?
save!
Poll::Voter.find_or_create_by!(user: author, poll: poll, origin: "web", token: token)
end
end
end