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
I was trying to use this:
if Business.where(:user_id => current_user.id) == nil # no business found end
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
~ Asked on 2013-05-22 02:49:12
Why your code does not work?
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
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
Option 1: Using
if Business.exists?(user_id: current_user.id) # same as Business.where(user_id: current_user.id).exists? # ... else # ... end
if Business.where(:user_id => current_user.id).present? # less efficiant than using .exists? (see generated SQL for .exists? vs .present?) else # ... end
Option 3: Variable assignment in the if statement
if business = Business.where(:user_id => current_user.id).first business.do_some_stuff else # do something else end
This option can be considered a code smell by some linters (Rubocop for example).
Option 3b: Variable assignment
business = Business.where(user_id: current_user.id).first if business # ... else # ... end
You can also use
.find_by_user_id(current_user.id) instead of
Businessobject(s): Option 1
Businessobject(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: current_user.id
~ Answered on 2013-06-26 17:34:08