为什么你的代码不起作用?
The where
方法返回一个ActiveRecord::关系对象(就像一个数组,其中包含where
), 它可以是空的,但它永远不会是空的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
如何测试是否至少存在一条记录?
选项1: Using .exists? http://apidock.com/rails/ActiveRecord/FinderMethods/exists%3F
if Business.exists?(user_id: current_user.id)
# same as Business.where(user_id: current_user.id).exists?
# ...
else
# ...
end
选项2: Using .present? http://apidock.com/rails/Object/present%3F (or .blank? http://apidock.com/rails/Object/blank%3F,相反.present?
)
if Business.where(:user_id => current_user.id).present?
# less efficiant than using .exists? (see generated SQL for .exists? vs .present?)
else
# ...
end
选项 3:if语句中的变量赋值
if business = Business.where(:user_id => current_user.id).first
business.do_some_stuff
else
# do something else
end
某些 linter(例如 Rubocop)可以将此选项视为代码异味。
选项 3b:变量赋值
business = Business.where(user_id: current_user.id).first
if business
# ...
else
# ...
end
您还可以使用.find_by_user_id(current_user.id)
代替.where(...).first
最佳选择:
- 如果您不使用
Business
对象:Option 1
- 如果您需要使用
Business
对象:Option 3