class method
self.exists?
Ruby on Rails 2.3.18
Since v2.2.3 Last seen in v2.3.18Available in: v2.2.3 v2.3.18
Signature
self.exists?(id_or_conditions = {})
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?
Parameters
-
id_or_conditionsopt = {}
Source
# File activerecord/lib/active_record/base.rb, line 693
def exists?(id_or_conditions = {})
find_initial(
:select => "#{quoted_table_name}.#{primary_key}",
:conditions => expand_id_conditions(id_or_conditions)) ? true : false
end
Defined in activerecord/lib/active_record/base.rb line 693
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::Base