ruby-on-rails 检查查询结果是否为空 (Model.find)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13790263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ruby-on-rails check if query result is empty (Model.find)
提问by Tobi89
i′m using ruby on rails and trying to check if a query is returning a value or not.
我在 rails 上使用 ruby 并尝试检查查询是否返回值。
This is the query:
这是查询:
@search = Customer.find_by_name($login_name)
If the query finds a result, everything is fine, but how can i react on empty results?
如果查询找到结果,一切都很好,但是我如何对空结果做出反应?
I tried:
我试过:
if @search.empty?
flash[:notice] = 'Username nicht bekannt'
redirect_to :action => :login
end
But i get an error:
但我收到一个错误:
undefined method `empty?' for nil:NilClass
Any Ideas what went wrong?
任何想法出了什么问题?
Thank you!!!
谢谢!!!
回答by Rahul garg
Use this to check for nil as well as empty cases:
使用它来检查 nil 和空情况:
@search.blank?
For the opposite case (NOT nil and NOT empty), use .present?:
@search.present? #equivalent of [email protected]?
The reason your query returned nilinstead of emptyis :
您的查询返回nil而不是的原因empty是:
Customer.find_by_name($login_name)
always returns one result of object Customeror nilif there is no such result,
总是返回对象的一个结果,Customer或者nil如果没有这样的结果,
while something like:
而像:
Customer.where(:name=>$login_name)
will return you ActiveRecord::Relation(which can have 0-n results) always. and empty?method will work on it
将ActiveRecord::Relation始终返回您(可以有 0-n 个结果)。和empty?方法将适用于它
回答by Fiona T
If no result is found, find_by_namereturns a nil object, rather than an empty array. To check whether a customer was found, you can use if @search.nil?or simply if !@searchor unless @search, since nil is falsy in ruby.
如果没有找到结果,则find_by_name返回一个 nil 对象,而不是一个空数组。要检查是否找到了客户,您可以if @search.nil?简单地使用if !@searchor unless @search,因为 nil 在 ruby 中是假的。
@search = Customer.find_by_name($login_name)
unless @search
flash[:notice] = 'Username nicht bekannt'
redirect_to :action => :login
end

