nickcharlton
nickcharlton

Reputation: 856

Checking if ActiveRecord find returns 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?

Upvotes: 18

Views: 34510

Answers (7)

Vlad Cenan
Vlad Cenan

Reputation: 172

Another way to do it is checking with ActiveRecord#any?.

Upvotes: 0

boulder_ruby
boulder_ruby

Reputation: 39763

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

Upvotes: 1

blocktator
blocktator

Reputation: 136

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

Upvotes: 2

Ryan Bigg
Ryan Bigg

Reputation: 107728

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.

Upvotes: 7

Cristobal Viedma
Cristobal Viedma

Reputation: 1020

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

post.empty?

will return true.

Upvotes: 4

Jordan Running
Jordan Running

Reputation: 106087

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

Upvotes: 27

shingara
shingara

Reputation: 46914

You can try ActiveRecord::Base.exists? before

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

Upvotes: 13

Related Questions