I don’t want user to delete all entries in database. There should be at
least one always present. How can I put this validation in model?
I don’t want user to delete all entries in database. There should be at
least one always present. How can I put this validation in model?
Something like this will stop the last record being deleted.
class Model < ActiveRecord::Base
before_destroy :ok_to_delete_last_record?
private
def ok_to_delete_last_record?
self.class.count > 1
end
end
Cheers,
Jordan
AWDwRoR catches it with this in the applicable model:
def after_destroy
if User.count.zero?
raise “Can’t delete last user”
end
end
It seems like it would already have deleted the record (since it’s
after_destroy), but it will still be there and raise the error before
the data goes away.
-Kyle