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?
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?
You can try ActiveRecord::Base.exists? before
Another way to do it is checking with ActiveRecord#any?.
if post doesn't contain any result it will be an empty list and then:
will return true.
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.If you didn't raise an exception here I believe that Rails would show the public/404.html page.
find :all
returns an empty array ([]
) if no rows are returned, so you can just use it this way: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 thefind_by
helper orfind :first
or justfirst
instead:will return nil rathering than blowing up your program when it can't find a record.
Of course, there's
which always returns an array of results. In which case you could just run an
or
or of course,
Sorry I got a little carried away there