检查ActiveRecord是否返回结果

nic*_*ton 17 ruby activerecord ruby-on-rails

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

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

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

Jor*_*ing 25

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

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

unless post.empty?
  # do something...
end
Run Code Online (Sandbox Code Playgroud)

顺便说一句,如果你这样做,find :all你将获得一个数组,而不是一行.如果您只想获得一个帖子,那么使用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
Run Code Online (Sandbox Code Playgroud)

  • 有一点,如果您只使用带主键的find()(不使用:all或:first),如果找不到任何内容,则会引发异常. (3认同)

shi*_*ara 12

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

Post.exists?(:conditions => { :url => params['url'] })
Run Code Online (Sandbox Code Playgroud)


Rya*_*igg 7

使用BANG!find_by_url无法找到使其引发异常的方法的版本,然后在同一方法/操作中将其解救.

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
Run Code Online (Sandbox Code Playgroud)

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