Why is your code not working?
The where method returns an ActiveRecord :: Relation object (acts like an array containing the results of where ), it may 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 check if at least one record exists?
Option 1: Using .exists?
if Business.exists?(user_id: current_user.id) # same as Business.where(user_id: current_user.id).exists? # ... else # ... end
Option 2: Using .present? (or .blank? opposite .present? )
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: Assigning a variable in an if statement
if business = Business.where(:user_id => current_user.id).first business.do_some_stuff else # do something else end
This parameter can be considered a smell of code by some linter (for example, Rubocop).
Option 3b: Assigning Variables
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 .where(...).first
The best way:
- If you are not using a
Business object: Option 1 - If you need to use
Business objects: Option 3
MrYoshiji May 22 '13 at 2:53 a.m. 2013-05-22 02:53
source share