Created
January 25, 2019 18:11
-
-
Save ErvalhouS/96cdeb22ec2e77e754c8c1cdc05ea34d to your computer and use it in GitHub Desktop.
An application record to enable some explicit method overriding to make discard behave just a little like paranoia or act_as_paranoid.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# An abstract model to allow common behavior to be inherited | |
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
include Discard::Model | |
default_scope -> { kept } | |
def destroy | |
discard | |
self.class.reflect_on_all_associations(:belongs_to).each do |association| | |
next unless association.try(:counter_cache_column).present? | |
association.klass | |
.decrement_counter(counter_column_name, | |
send(association.foreign_key)) | |
end | |
end | |
def undiscard | |
super | |
self.class.reflect_on_all_associations(:belongs_to).each do |association| | |
next unless association.try(:counter_cache_column).present? | |
association.klass | |
.increment_counter(counter_column_name, | |
send(association.foreign_key)) | |
end | |
end | |
def counter_column_name | |
(self.class.name.underscore.pluralize + '_count').to_sym | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment