Check if record exists from controller in Rails


In my app a User can create a Business. When they trigger the index action in my BusinessesController I want to check if a Business is related to the

  • If yes: display the business.
  • If no: redirect to the new action.

I was trying to use this:

if Business.where(:user_id => == nil
  # no business found

But it always returns true even when the business doesn't exist...

How can I test if a record exists in my database?

This question is tagged with ruby-on-rails ruby-on-rails-3 activerecord exists

~ Asked on 2013-05-22 02:49:12

The Best Answer is


Why your code does not work?

The where method returns an ActiveRecord::Relation object (acts like an array which contains the results of the where), it can be empty but it will never be nil.

Business.where(id: -1) 
 #=> returns an empty ActiveRecord::Relation ( similar to an array )
Business.where(id: -1).nil? # ( similar to == nil? )
 #=> returns false
Business.where(id: -1).empty? # test if the array is empty ( similar to .blank? )
 #=> returns true

How to test if at least one record exists?

Option 1: Using .exists?

if Business.exists?(user_id:
  # same as Business.where(user_id:
  # ...
  # ...

Option 2: Using .present? (or .blank?, the opposite of .present?)

if Business.where(:user_id =>
  # less efficiant than using .exists? (see generated SQL for .exists? vs .present?)
  # ...

Option 3: Variable assignment in the if statement

if business = Business.where(:user_id =>
  # do something else

This option can be considered a code smell by some linters (Rubocop for example).

Option 3b: Variable assignment

business = Business.where(user_id:
if business
  # ...
  # ...

You can also use .find_by_user_id( instead of .where(...).first

Best option:

  • If you don't use the Business object(s): Option 1
  • If you need to use the Business object(s): Option 3

~ Answered on 2013-05-22 02:53:00


In this case I like to use the exists? method provided by ActiveRecord:

Business.exists? user_id:

~ Answered on 2013-06-26 17:34:08

Most Viewed Questions: