views:

56

answers:

5

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?

+2  A: 

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

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
Jordan
One point of interest, if you just use find() with the primary key (not using :all or :first), it raises an exception if nothing was found.
Zachary
+1  A: 

You can try ActiveRecord::Base.exists? before

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

if post doesn't contain any result it will be an empty list and then:

post.empty?

will return true.

Cristobal Viedma
A: 

Use the BANG! version of the find_by_url method to get it to raise an exception of it could not be found and then rescue it later on in that same method/action.

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

If you didn't raise an exception here I believe that Rails would show the public/404.html page.

Ryan Bigg
+1  A: 

it may be as simple as changing your finder to:

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

With this finder, post will either return a single value or nil. Because nil behaves like false in a condition statement, you can say something like the following:

if post
  # do something
else
  # do something else
end
jamin4jc