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\'] },
Post.find_by_id(id_column_value)
will return nil rathering than blowing up your program when it can't find a record.
Of course, there's
x = Post.where(:any_column_name => value)
which always returns an array of results. In which case you could just run an
x.each {|t| f(t) }
or
y = x.map {|t| f(t)}
or of course,
x[0], x[1], etc
Sorry I got a little carried away there
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.
if post doesn't contain any result it will be an empty list and then:
post.empty?
will return true.
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
Another way to do it is checking with ActiveRecord#any?.
You can try ActiveRecord::Base.exists? before
Post.exists?(:conditions => { :url => params['url'] })