Extract method to get valid answers to a question

This way we remove duplication and we avoid a multi-line block in a
validation rule, which made the code hard to read.
This commit is contained in:
Javi Martín
2019-09-30 13:08:08 +02:00
parent 657f8d129c
commit d42b9ff4a5
3 changed files with 6 additions and 7 deletions

View File

@@ -9,9 +9,7 @@ class Poll::Answer < ApplicationRecord
validates :author, presence: true
validates :answer, presence: true
validates :answer, inclusion: { in: ->(a) { a.question.question_answers
.joins(:translations)
.pluck("poll_question_answer_translations.title") }},
validates :answer, inclusion: { in: ->(a) { a.question.possible_answers }},
unless: ->(a) { a.question.blank? }
scope :by_author, ->(author_id) { where(author_id: author_id) }

View File

@@ -10,10 +10,7 @@ class Poll::PartialResult < ApplicationRecord
validates :question, presence: true
validates :author, presence: true
validates :answer, presence: true
validates :answer, inclusion: { in: ->(a) { a.question.question_answers
.visibles
.joins(:translations)
.pluck("poll_question_answer_translations.title") }},
validates :answer, inclusion: { in: -> (a) { a.question.possible_answers }},
unless: ->(a) { a.question.blank? }
validates :origin, inclusion: { in: VALID_ORIGINS }

View File

@@ -87,4 +87,8 @@ class Poll::Question < ApplicationRecord
def is_positive_negative?
votation_type.present? && enum_type == "positive_negative_open"
end
def possible_answers
question_answers.visibles.joins(:translations).pluck("poll_question_answer_translations.title")
end
end