method

exists?

Importance_5
v2.3.8 - Show latest stable - 4 notes - Class: ActiveRecord::Base
exists?(id_or_conditions = {}) public

Returns true if a record exists in the table that matches the id or conditions given, or false otherwise. The argument can take five forms:

  • Integer - Finds the record with this primary key.
  • String - Finds the record with a primary key corresponding to this string (such as '5').
  • Array - Finds the record that matches these find-style conditions (such as ['color = ?', 'red']).
  • Hash - Finds the record that matches these find-style conditions (such as {:color => 'red'}).
  • No args - Returns false if the table is empty, true otherwise.

For more information about specifying conditions as a Hash or Array, see the Conditions section in the introduction to ActiveRecord::Base.

Note: You can’t pass in a condition as a string (like name = 'Jamie'), since it would be sanitized and then queried against the primary key column, like id = 'name = \'Jamie\''.

Examples

  Person.exists?(5)
  Person.exists?('5')
  Person.exists?(:name => "David")
  Person.exists?(['name LIKE ?', "%#{query}%"])
  Person.exists?
Show source
Register or log in to add new notes.
February 3, 2009
3 thanks

Possible gotcha

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!
January 30, 2009 - (<= v2.1.0)
3 thanks

Hash conditions require explicit key and value

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)
September 9, 2010
2 thanks

takes ActiveRecord object as an arg as well

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”.

April 22, 2010
2 thanks

Dynamic exists? methods

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")