exists?(conditions = :none) public

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 always false.

  • No args - Returns false if the relation 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\''.

Person.exists?(['name LIKE ?', "%#{query}%"])
Person.exists?(id: [1, 4, 8])
Person.exists?(name: 'David')
Person.where(name: 'Spartacus', rating: 4).exists?
Show source
Register or log in to add new notes.
August 11, 2011
2 thanks

More AREL compliant style is also possible

Code example

Person.where(:name => 'David').exists?