How to check if a table is empty in Rails

You may already know that if you want to check for the existence of an Active Record object you can use a method called exists? Let’s say you have a User model and would like to know if a record exists with a matching primary id:

User.exists?(1)               # returns true if a user with matching id of 1 exists and false otherwise.
User.exists?(:name => 'John') # also works with find-style conditionals

It’s also possible to use exists? without any arguments on a model to see if the table is empty:

User.exists? # returns false if the users table is empty and true otherwise.

Additionally, you can use User.any? and User.many? instead of exists? to check for existence on a model or relation.

One Comment

  1. Wes Gamble
    September 4, 2014

    Never knew this. Thanks! I always did a User.count to see how many records were in the table.

Leave a Reply

Your email address will not be published. Required fields are marked *