检查是否存在记录从Rails的控制器 [英] Check if record exists from controller in Rails
问题描述
在我的应用程序,用户可以创建业务。当他们触发首页
在行动我的 BusinessesController
我要检查,如果一个企业是关系到 current_user.id
:
In my app a User can create a Business. When they trigger the index
action in my BusinessesController
I want to check if a Business is related to the current_user.id
:
- 如果是:显示业务。
- 如果没有:重定向到
新
的行动。
- If yes: display the business.
- If no: redirect to the
new
action.
我试图用这样的:
if Business.where(:user_id => current_user.id) == nil
# no business found
end
但它总是甚至当企业不存在返回true ...
But it always returns true even when the business doesn't exist...
如何测试是否存在记录在我的数据库?
推荐答案
为什么你code不起作用?
在其中,
方法返回一个的ActiveRecord ::关系对象(作用类似,其中包含了的结果数组其中,
),它可以是空的,但它决不会零
The where
method returns an ActiveRecord::Relation object (acts like an array which contains the results of the where
), it can be empty but it will never be 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
How to test if a record exists?
Option 1: Using .exists?
if Business.exists?(:user_id => current_user.id)
# ...
else
# ...
end
选项2:使用 present ?
(或 .blank?
中,。present相反?
)
Option 2: Using .present?
(or .blank?
, the opposite of .present?
)
if Business.where(:user_id => current_user.id).present?
# ...
else
# ...
end
选项3:在变量赋值的if语句
Option 3: Variable assignment in the if statement
if business = Business.where(:user_id => current_user.id).first
business.do_some_stuff
else
# do something else
end
您也可以使用 .find_by_user_id(current_user.id)
而不是。凡(...)。第一个
这篇关于检查是否存在记录从Rails的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!