Check if record exists from controller in Rails -
in app user can create business. when trigger index action in businessescontroller want check if business related current_user.id:
- if yes: display business.
- if no: redirect
newaction.
i trying use this:
if business.where(:user_id => current_user.id) == nil # no business found end but returns true when business doesn't exist...
how can test if record exists in database?
why code not work?
the where method returns activerecord::relation object (acts array contains results of where), it can empty never nil.
business.where(id: -1) #=> returns empty activerecord::relation ( similar array ) business.where(id: -1).nil? # ( similar == nil? ) #=> returns false business.where(id: -1).empty? # test if array empty ( similar .blank? ) #=> returns true how test if record exists?
option 1: using .exists?
if business.exists?(user_id: current_user.id) # same business.where(user_id: current_user.id).exists? # ... else # ... end option 2: using .present? (or .blank?, opposite of .present?)
if business.where(:user_id => current_user.id).present? # less efficiant using .exists? (see generated sql .exists? vs .present?) else # ... end option 3: variable assignment in if statement
if business = business.where(:user_id => current_user.id).first business.do_some_stuff else # else end option 3b: variable assignment
business = business.where(user_id: current_user.id).first if business # ... else # ... end you can use .find_by_user_id(current_user.id) instead of .where(...).first
best option:
- if don't use
businessobject(s): option 1 - if need use
businessobject(s): option 3
Comments
Post a Comment