如果检查发现的ActiveRecord返回结果 [英] Checking if ActiveRecord find returns a result
本文介绍了如果检查发现的ActiveRecord返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检查是否找到方法返回一个结果。我找到方法如下:
I'm trying to check if a find method returns a result. My find method is the following:
post = Post.find(:all, :conditions => { :url => params['url'] }, :limit => 1)
什么是检查后
中包含的结果呢?一个好办法
What would be a good way to check that post
contains a result?
推荐答案
查找:所有
返回一个空数组( []
),如果没有返回行,所以你可以用这种方式:
find :all
returns an empty array ([]
) if no rows are returned, so you can just use it this way:
post = Post.find(:all, :conditions => { :url => params['url'] }, :limit => 1)
unless post.empty?
# do something...
end
顺便说一句,如果你这样做查找:所有
你会得到一个数组,而不是单行。如果你想得到的只是一个职位,那将是更清洁的使用 find_by
助手或发现:第一个
或只是第一
来代替:
By the way, if you do find :all
you're going to get an array, not a single row. If you're trying to get just one Post, it would be cleaner to use the find_by
helper or find :first
or just first
instead:
post = Post.find_by_url params['url']
# or
post = Post.first :conditions => { :url => params['url'] }
# then...
if post
# do something...
end
这篇关于如果检查发现的ActiveRecord返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文