Merge pull request #1108 from Retrospring/refactor/counters

Use Rails built-in counters for associations
This commit is contained in:
Karina Kwiatek 2023-03-07 10:54:55 +01:00 committed by GitHub
commit df9ce09dfe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 4 additions and 17 deletions

View File

@ -1,8 +1,8 @@
class Answer < ApplicationRecord
extend Answer::TimelineMethods
belongs_to :user
belongs_to :question
belongs_to :user, counter_cache: :answered_count
belongs_to :question, counter_cache: :answer_count
has_many :comments, dependent: :destroy
has_many :smiles, class_name: "Appendable::Reaction", foreign_key: :parent_id, dependent: :destroy
has_many :subscriptions, dependent: :destroy
@ -18,15 +18,12 @@ class Answer < ApplicationRecord
SHORT_ANSWER_MAX_LENGTH = 640
# rubocop:disable Rails/SkipsModelValidations
after_create do
Inbox.where(user: self.user, question: self.question).destroy_all
Notification.notify self.question.user, self unless self.question.user == self.user or self.question.user.nil?
Subscription.subscribe self.user, self
Subscription.subscribe self.question.user, self unless self.question.author_is_anonymous
user.increment! :answered_count
question.increment! :answer_count
end
before_destroy do
@ -39,19 +36,15 @@ class Answer < ApplicationRecord
end
end
user&.decrement! :answered_count
question&.decrement! :answer_count
self.smiles.each do |smile|
Notification.denotify self.user, smile
end
self.comments.each do |comment|
comment.user&.decrement! :commented_count
Subscription.denotify comment, self
end
Notification.denotify question&.user, self
Subscription.destruct self
end
# rubocop:enable Rails/SkipsModelValidations
def notification_type(*_args)
Notification::QuestionAnswered

View File

@ -1,18 +1,15 @@
class Comment < ApplicationRecord
belongs_to :user
belongs_to :answer
belongs_to :user, counter_cache: :commented_count
belongs_to :answer, counter_cache: :comment_count
validates :user_id, presence: true
validates :answer_id, presence: true
has_many :smiles, class_name: "Appendable::Reaction", foreign_key: :parent_id, dependent: :destroy
validates :content, length: { maximum: 512 }
# rubocop:disable Rails/SkipsModelValidations
after_create do
Subscription.subscribe self.user, answer, false
Subscription.notify self, answer
user.increment! :commented_count
answer.increment! :comment_count
end
before_destroy do
@ -25,10 +22,7 @@ class Comment < ApplicationRecord
end
Subscription.denotify self, answer
user&.decrement! :commented_count
answer&.decrement! :comment_count
end
# rubocop:enable Rails/SkipsModelValidations
def notification_type(*_args)
Notification::Commented