method

exists?

exists?(id_or_conditions)
public

Checks whether a record exists in the database that matches conditions given. These conditions can either be a single integer representing a primary key id to be found, or a condition to be matched like using ActiveRecord#find.

The id_or_conditions parameter can be an Integer or a String if you want to search the primary key column of the table for a matching id, or if you’re looking to match against a condition you can use an Array or a Hash.

Possible gotcha: You can’t pass in a condition as a string e.g. "name = ‘Jamie’", this would be sanitized and then queried against the primary key column as "id = ‘name = \’Jamie"

Examples

  Person.exists?(5)
  Person.exists?('5')
  Person.exists?(:name => "David")
  Person.exists?(['name LIKE ?', "%#{query}%"])

4Notes

Hash conditions require explicit key and value

zakmandhro · Jan 30, 20093 thanks

When condition passed as hash, the behavior is different from a finder method. Finder methods, such as:

find(:all, :user=>user)

will apply the user_id = user.id convention, provided user is an association (e.g. belongs_to :user). The exists? method will not do the same. You must specify the foreign key name and value explicitly, i.e:

exists?(:user_id=>user.id)

Possible gotcha

szeryf · Feb 3, 20093 thanks

Please note that +exists?+ doesn't hold all the conventions of +find+, i.e. you can't do:

Person.exists?(:conditions => ['name LIKE ?', "%#{query}%"]) # DOESN'T WORK!

Dynamic exists? methods

szeryf · Apr 22, 20102 thanks

There are no dynamic exists? methods analogous to dynamic finders, which means that while you can do this:

Person.find_by_name('David')

you can't do this:

Person.exists_by_name('David') # DOES NOT WORK

nor this:

Person.exists_by_name?('David') # DOES NOT WORK

However, you can simulate this with dynamic scope:

Person.scoped_by_name('David').exists?

You'll have to admit that this is so much better than the plain old method:

Person.exists?(:name => "David")

takes ActiveRecord object as an arg as well

carpeliam · Sep 8, 20102 thanks

One undocumented feature, you can do this: person = Person.first Person.exists?(person) # => returns true This came in handy for me when I needed to see if something belonged to a particular scope.

scope = "created_rails"
person = Person.find_by_name "dhh"
Person.send(scope).exists?(person)
# => returns true

Obviously this relies on you having a named_scope in your Person model called "created_rails".