检查 Rails 控制器中的记录是否存在

2024-03-04

在我的应用程序中,用户可以创建业务。当他们触发index行动在我的BusinessesController我想检查某个企业是否与current_user.id:

  • 如果是:显示该业务。
  • 如果没有:重定向到new行动。

我试图用这个:

if Business.where(:user_id => current_user.id) == nil
  # no business found
end

但即使业务不存在,它也总是返回 true ......

如何测试数据库中是否存在记录?


为什么你的代码不起作用?

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

检查 Rails 控制器中的记录是否存在 的相关文章

随机推荐