instance method exists?

Ruby on Rails 4.2.9

Since v3.0.20

Available in: v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

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 find-style conditions (such as ['name LIKE ?', "%#{query}%"]).

  • Hash - Finds the record that matches these find-style conditions (such as {name: 'David'}).

  • false - Returns always false.

  • 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\''.

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?

Parameters

conditions opt = :none
Source
# File activerecord/lib/active_record/relation/finder_methods.rb, line 277
    def exists?(conditions = :none)
      if Base === conditions
        conditions = conditions.id
        ActiveSupport::Deprecation.warn(<<-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

      relation = apply_join_dependency(self, construct_join_dependency)
      return false if ActiveRecord::NullRelation === relation

      relation = relation.except(:select, :order).select(ONE_AS_ONE).limit(1)

      case conditions
      when Array, Hash
        relation = relation.where(conditions)
      else
        unless conditions == :none
          relation = relation.where(primary_key => conditions)
        end
      end

      connection.select_value(relation, "#{name} Exists", relation.arel.bind_values + relation.bind_values) ? true : false
    end

Defined in activerecord/lib/active_record/relation/finder_methods.rb line 277 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::FinderMethods

Type at least 2 characters to search.

↑↓ navigate · open · esc close