I have a Ruby on Rails application for human resource planning. Normally, it is not allowed to delete entries from the past. From time to time, however, I have to delete users and, of course, I want to delete all entries from these users.
My user model:
has_many :team_memberships, dependent: :destroy
has_many :slots, through: :team_memberships, source: :slot
TeamMembership model:
before_destroy :check_permission
def check_permission
if self.slot.start_time < Time.now.beginning_of_day
errors.add(:base, "Historische Einträge können nicht gelöscht werden")
return false
end
end
I have a rake task that should destroy old users, but that doesn't work when they have historical entries because the validation fails.
How can I skip the before_destroy validation when User.destroy is called via a rake task? Any ideas?
You could add a new method to your model that set a variable and use that as a return value of the callback:
before_destroy :check_permission
def allow_deletion!
@allow_deletion = true
end
def check_permission
if !@allow_deletion && self.slot.start_time < Time.now.beginning_of_day
errors.add(:base, "Historische Einträge können nicht gelöscht werden")
return false
end
end
That allows you to write something like this:
user.allow_deletion!
user.destroy
This method has the benefit over delete that you only skip this specific callback and not all callbacks and dependent destroy operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With