Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 368
nickcharlton Avatar asked May 19 '10 14:05

nickcharlton


People also ask

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What are ActiveRecord methods?

Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format, and many more.

What is Ruby ActiveRecord?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


2 Answers

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
like image 144
Jordan Running Avatar answered Oct 14 '22 20:10

Jordan Running


You can try ActiveRecord::Base.exists? before

Post.exists?(:conditions => { :url => params['url'] })
like image 42
shingara Avatar answered Oct 14 '22 20:10

shingara