class method self.exists?

Ruby on Rails 2.2.3

Since v2.2.3 Last seen in v2.3.18

Available in: v2.2.3 v2.3.18

Signature

self.exists?(id_or_conditions)

Checks whether a record exists in the database that matches conditions given. These conditions can either be a single integer representing a primary key id to be found, or a condition to be matched like using ActiveRecord#find.

The id_or_conditions parameter can be an Integer or a String if you want to search the primary key column of the table for a matching id, or if you’re looking to match against a condition you can use an Array or a Hash.

Possible gotcha: You can’t pass in a condition as a string e.g. “name = ‘Jamie’”, this would be sanitized and then queried against the primary key column as “id = ‘name = \’Jamie”

Examples

Person.exists?(5)
Person.exists?('5')
Person.exists?(:name => "David")
Person.exists?(['name LIKE ?', "%#{query}%"])

Parameters

id_or_conditions req
Source
# File activerecord/lib/active_record/base.rb, line 654
      def exists?(id_or_conditions)
        connection.select_all(
          construct_finder_sql(
            :select     => "#{quoted_table_name}.#{primary_key}",
            :conditions => expand_id_conditions(id_or_conditions),
            :limit      => 1
          ),
          "#{name} Exists"
        ).size > 0
      end

Defined in activerecord/lib/active_record/base.rb line 654 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::Base

Type at least 2 characters to search.

↑↓ navigate · open · esc close