exists?
- 1.0.0 (0)
- 1.1.6 (0)
- 1.2.6 (5)
- 2.0.3 (17)
- 2.1.0 (0)
- 2.2.1 (0)
- 2.3.8 (11)
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
exists?(id)
public
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!
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)
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”.
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")