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 current_user.id
:
- If yes: display the business.
- If no: redirect to the
new
action.
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?
In this case I like to use the
exists?
method provided by ActiveRecord:with 'exists?':
with 'any?':
If you use something with .where, be sure to avoid trouble with scopes and better use .unscoped
When you call
Business.where(:user_id => current_user.id)
you will get an array. This Array may have no objects or one or many objects in it, but it won't be null. Thus the check == nil will never be true.You can try the following:
So you check the number of elements in the array and compare them to zero.
or you can try:
this will return one or nil.
ActiveRecord#where will return an ActiveRecord::Relation object (which will never be nil). Try using .empty? on the relation to test if it will return any records.
Why your code does not work?
The
where
method returns an ActiveRecord::Relation object (acts like an array which contains the results of thewhere
), it can be empty but it will never benil
.How to test if at least one record exists?
Option 1: Using
.exists?
Option 2: Using
.present?
(or.blank?
, the opposite of.present?
)Option 3: Variable assignment in the if statement
This option can be considered a code smell by some linters (Rubocop for example).
Option 3b: Variable assignment
You can also use
.find_by_user_id(current_user.id)
instead of.where(...).first
Best option:
Business
object(s): Option 1Business
object(s): Option 3