-
Notifications
You must be signed in to change notification settings - Fork 0
/
answer.rb
35 lines (28 loc) · 826 Bytes
/
answer.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Answer < ApplicationRecord
belongs_to :user
belongs_to :question
has_many_attached :files
default_scope { order(best: :desc, created_at: :asc) }
scope :best, -> { where(best: true) }
validates :body, presence: true,
length: { minimum: 50 }
validate :only_one_best_per_question
def mark_as_best
transaction do
question.answers.best.update_all(best: false)
self.update!(best: true)
end
end
private
def only_one_best_per_question
return unless best?
return unless question&.answers.best.any?
if persisted?
# update
errors.add(:best, :there_is_the_best_answer_in_question_already) if changes['best'] == [false, true]
else
# create
errors.add(:best, :there_is_the_best_answer_in_question_already)
end
end
end