# Validation for at least one record in database

**URL:** <https://www.ruby-forum.com/t/validation-for-at-least-one-record-in-database/133859>\
**Category:** Rails\
**Created:** [April 4, 2008, 1:53pm UTC](https://www.ruby-forum.com/t/validation-for-at-least-one-record-in-database/133859 "2008-04-04T13:53:46Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![vapor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/5e9695/32.png) [@vapor](https://www.ruby-forum.com/u/vapor)\
**Post date:** [April 4, 2008, 1:53pm UTC](https://www.ruby-forum.com/t/validation-for-at-least-one-record-in-database/133859/1 "2008-04-04T13:53:46Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![vapor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/5e9695/32.png) [@vapor](https://www.ruby-forum.com/u/vapor)\
**Post date:** [April 4, 2008, 2:57pm UTC](https://www.ruby-forum.com/t/validation-for-at-least-one-record-in-database/133859/2 "2008-04-04T14:57:33Z")

</div>

> 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

---

<div class="post-metadata">

**Author:** ![vapor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/5e9695/32.png) [@vapor](https://www.ruby-forum.com/u/vapor)\
**Post date:** [April 4, 2008, 9:34pm UTC](https://www.ruby-forum.com/t/validation-for-at-least-one-record-in-database/133859/3 "2008-04-04T21:34:07Z")

</div>

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
