Files
grecia/app/models/poll/pair_answer.rb
Javi Martín 42d2e5b3ad Apply Rails/InverseOf rubocop rule
Not doing so has a few gotchas when working with relations, particularly
with records which are not stored in the database.

I'm excluding the related content file because it's got a very peculiar
relationship with itself: the `has_one :opposite_related_content` has no
inverse; the relation itself is its inverse. It's a false positive since
the inverse condition is true:

```
content.opposite_related_content.opposite_related_content.object_id ==
  content.object_id
```
2019-10-25 19:29:12 +02:00

33 lines
1.3 KiB
Ruby

class Poll::PairAnswer < ApplicationRecord
belongs_to :question, -> { with_hidden }, inverse_of: :pair_answers
belongs_to :author, -> { with_hidden }, class_name: "User", inverse_of: :poll_pair_answers
belongs_to :answer_right, class_name: "Poll::Question::Answer"
belongs_to :answer_left, class_name: "Poll::Question::Answer"
delegate :poll, :poll_id, to: :question
validates :question, presence: true
validates :author, presence: true
validates :answer_left, presence: true
validates :answer_right, presence: true
validates :answer_left, inclusion: { in: ->(a) { a.question.question_answers.visibles }},
unless: ->(a) { a.question.blank? }
validates :answer_right, inclusion: { in: ->(a) { a.question.question_answers.visibles }},
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 self.generate_pair(question, user)
answers = question.question_answers.visibles.sample(2)
question.pair_answers.by_author(user).map(&:destroy)
question.pair_answers.create(author: user, answer_left: answers[0], answer_right: answers[1])
end
def answers
[answer_left, answer_right].compact
end
end