Returns true if the given id represents the primary key of a record in the database, false otherwise. You can also pass a set of SQL conditions. Example:
# File activerecord/lib/active_record/base.rb, line 434 def exists?(id_or_conditions) !find(:first, :conditions => expand_id_conditions(id_or_conditions)).nil? rescue ActiveRecord::ActiveRecordError false end
When condition passed as hash, the behavior is different from a finder method. Finder methods, such as:
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:
There are no dynamic exists? methods analogous to dynamic finders, which means that while you can do this:
you can’t do this:
Person.exists_by_name('David') # DOES NOT WORK
Person.exists_by_name?('David') # DOES NOT WORK
However, you can simulate this with dynamic scope:
You’ll have to admit that this is so much better than the plain old method:
One undocumented feature, you can do this:
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”.