检查ActiveRecord是否返回结果

我正在尝试检查find方法是否返回结果。 我的find方法如下:

post = Post.find(:all, :conditions => { :url => params['url'] }, :limit => 1) 

检查该post包含结果的好方法是什么?

find :all如果没有返回任何行,则find :all返回一个空数组( [] ),所以你可以这样使用它:

 post = Post.find(:all, :conditions => { :url => params['url'] }, :limit => 1) unless post.empty? # do something... end 

顺便说一句,如果你确实find :all你将得到一个数组,而不是一行。 如果您只想获得一个post,那么使用find_by帮助器或find :first或只是first

 post = Post.find_by_url params['url'] # or post = Post.first :conditions => { :url => params['url'] } # then... if post # do something... end 

你可以尝试ActiveRecord :: Base.exists? 之前

 Post.exists?(:conditions => { :url => params['url'] }) 

使用BANG! find_by_url方法的版本,以使其无法找到它的exception,然后在相同的方法/操作中解救它。

 def show Post.find_by_url!(params[:url]) rescue ActiveRecord::RecordNotFound flash[:notice] = "The URL you were looking for could not be found." redirect_to root_path end end 

如果您没有在此处引发exception,我相信Rails会显示public / 404.html页面。

如果post不包含任何结果,那么它将是一个空列表,然后:

 post.empty? 

将返回true。

它可能就像将您的取景器更改为:

 post = Post.find(:first, :conditions => { :url => params['url'] }) 

使用此finder,post将返回单个值或nil。 因为nil在条件语句中的行为类似于false,所以您可以这样说:

 if post # do something else # do something else end 
 Post.find_by_id(id_column_value) 

当它无法找到记录时,将返回nil而不是炸毁你的程序。

当然,有

 x = Post.where(:any_column_name => value) 

它总是返回一组结果。 在这种情况下你可以运行一个

 x.each {|t| f(t) } 

要么

 y = x.map {|t| f(t)} 

当然,

 x[0], x[1], etc 

对不起,我有点被带走了

另一种方法是使用ActiveRecord#any检查? 。