Ruby on rails 检查Rails中是否存在来自控制器的记录
在我的应用程序中,用户可以创建业务。当他们在myRuby on rails 检查Rails中是否存在来自控制器的记录,ruby-on-rails,ruby-on-rails-3,activerecord,exists,Ruby On Rails,Ruby On Rails 3,Activerecord,Exists,在我的应用程序中,用户可以创建业务。当他们在myBusinessController中触发index操作时,我想检查业务是否与当前用户id相关: 如果是:显示业务 如果否:重定向到新建操作 我试着用这个: if Business.where(:user_id => current_user.id) == nil # no business found end 但即使业务不存在,它也会返回真值 如何测试数据库中是否存在记录?为什么代码不起作用? where方法返回一个ActiveR
BusinessController
中触发index
操作时,我想检查业务是否与当前用户id相关:
- 如果是:显示业务李>
- 如果否:重定向到
操作李>新建
if Business.where(:user_id => current_user.id) == nil
# no business found
end
但即使业务不存在,它也会返回真值
如何测试数据库中是否存在记录?为什么代码不起作用?
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:使用
选项2:使用(或者,与
.present?
相反)
选项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\u by\u user\u id(current\u user.id)
而不是。其中(…).first
最佳选择:
- 如果您不使用
对象:选项1业务
- 如果您需要使用
对象:选项3业务
业务时。其中(:user\u id=>current\u user.id)
您将获得一个数组。此数组中可能没有对象,也可能有一个或多个对象,但它不会为null。因此,check==nil永远不会为真
您可以尝试以下操作:
if Business.where(:user_id => current_user.id).count == 0
因此,检查数组中的元素数,并将它们与零进行比较
或者您可以尝试:
if Business.find_by_user_id(current_user.id).nil?
这将返回一或零。在这种情况下,我喜欢使用ActiveRecord提供的
exists?
方法:
Business.com是否存在?用户标识:当前用户标识
带有“存在”字样:
Business.exists? user_id: current_user.id #=> 1 or nil
“有吗?”
Business.where(:user_id => current_user.id).any? #=> true or false
如果您将某物与.where一起使用,请确保避免范围方面的问题,并更好地使用
如果需要使用对象的实例变量,我会这样做:
if @business = Business.where(:user_id => current_user.id).first
#Do stuff
else
#Do stuff
end
那似乎不起作用。它一直通过测试并加载索引html,就像==nil测试一样(因此我得到一个错误:nil:NilClass的未定义方法'name')。在调用presentOh之前尝试使用first。这是我的错,我很困惑,您需要使用
blank?
进行测试,谢谢您的帮助!我不该注意到那个错误。你能告诉我为什么==nil检查不起作用吗?是的,请给我一分钟,我会更新我的答案,也不要在之前使用。首先。空白?
;)如果没有记录,则使用where
将返回空数组。而[]
不等于nil
除非是业务。按用户id(当前用户id)查找\u
?可能与更好使用的业务重复。未范围。其中(:用户id=>当前用户id)。点击(:id)。有吗?为避免对正在检查的对象不必要地加载关系。是否存在?有还是可能?
Business.where(:user_id => current_user.id).any? #=> true or false
Business.unscoped.where(:user_id => current_user.id).any?
business = Business.where(:user_id => current_user.id).first
if business.nil?
# no business found
else
# business.ceo = "me"
end
if @business = Business.where(:user_id => current_user.id).first
#Do stuff
else
#Do stuff
end