Last active
August 29, 2015 14:19
-
-
Save groteck/373573ebf2ba737e6879 to your computer and use it in GitHub Desktop.
soft deleted if model has associations
This file contains hidden or 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
| module SoftDeletable | |
| extend ActiveSupport::Concern | |
| class ModelHasAssignedValues < StandardError; end | |
| included do | |
| scope :deleted, ->{ where.not(deleted: true) } | |
| scope :without_deleted, ->{ where(deleted: false) } | |
| scope :with_deleted, ->{ unscope(where: :deleted) } | |
| default_scope { without_deleted } | |
| before_destroy :associations_controller | |
| end | |
| def associations_controller | |
| self.class.reflect_on_all_associations.each do |assoc| | |
| message = "This #{self.class} has associated #{assoc.name}" | |
| excp = ModelHasAssignedValues.new(message) | |
| raise excp unless self.send(assoc.name).blank? | |
| end | |
| end | |
| def destroy | |
| begin | |
| run_callbacks :destroy | |
| super() | |
| rescue ModelHasAssignedValues => e | |
| self.errors.add(:delete, e.message) | |
| update(deleted_at: Time.zone.now, deleted: true) | |
| true | |
| end | |
| end | |
| def restore | |
| update(deleted_at: nil, deleted: false) | |
| end | |
| def deleted? | |
| deleted | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment