用户可以在我的应用中创建业务。当他们触发index我的操作时,我BusinessesController要检查某个业务是否与current_user.id:
- 如果是:显示业务。
- 如果否:重定向到
new操作。
我试图用这个:
if Business.where(:user_id => current_user.id) == nil
# no business found
end
但是即使业务不存在,它也总是返回true。
如何测试数据库中是否存在记录?
用户可以在我的应用中创建业务。当他们触发index我的操作时,我BusinessesController要检查某个业务是否与current_user.id:
new操作。我试图用这个:
if Business.where(:user_id => current_user.id) == nil
# no business found
end
但是即使业务不存在,它也总是返回true。
如何测试数据库中是否存在记录?
unless Business.find_by_user_id(current_user.id)呢?
Answers:
为什么您的代码不起作用?
该where方法返回ActiveRecord :: Relation对象(作用类似于包含的结果的数组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:使用.exists?
if Business.exists?(user_id: current_user.id)
# same as Business.where(user_id: current_user.id).exists?
# ...
else
# ...
end
选项2:使用.present?(或.blank?,与之相反.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
一些棉短绒(例如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对象:选项1Business对象:选项3blank?
在这种情况下,我喜欢使用exists?ActiveRecord提供的方法:
Business.exists? user_id: current_user.id
business = Business.where(:user_id => current_user.id).first
if business.nil?
# no business found
else
# business.ceo = "me"
end
where如果没有记录,使用将返回一个空数组。而且[]并不相等nil