instance method
exists?
Ruby on Rails 6.1.7.10
Since v3.0.20Signature
exists?(conditions = :none)
Returns true if a record exists in the table that matches the id or conditions given, or false otherwise. The argument can take six 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
where-style conditions (such as['name LIKE ?', "%#{query}%"]). -
Hash - Finds the record that matches these
where-style conditions (such as{name: 'David'}). -
false- Returns alwaysfalse. -
No args - Returns
falseif the relation is empty,trueotherwise.
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\''.
Person.exists?(5) Person.exists?('5') Person.exists?(['name LIKE ?', "%#{query}%"]) Person.exists?(id: [1, 4, 8]) Person.exists?(name: 'David') Person.exists?(false) Person.exists? Person.where(name: 'Spartacus', rating: 4).exists?
Parameters
-
conditionsopt = :none
Source
# File activerecord/lib/active_record/relation/finder_methods.rb, line 302
def exists?(conditions = :none)
if Base === conditions
raise ArgumentError, <<-MSG.squish
You are passing an instance of ActiveRecord::Base to `exists?`.
Please pass the id of the object by calling `.id`.
MSG
end
return false if !conditions || limit_value == 0
if eager_loading?
relation = apply_join_dependency(eager_loading: false)
return relation.exists?(conditions)
end
relation = construct_relation_for_exists(conditions)
return false if relation.where_clause.contradiction?
skip_query_cache_if_necessary { connection.select_rows(relation.arel, "#{name} Exists?").size == 1 }
end
Defined in activerecord/lib/active_record/relation/finder_methods.rb line 302
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::FinderMethods