Method: Dynamoid::Document::ClassMethods#exists?

Defined in:
lib/dynamoid/document.rb

#exists?(id_or_conditions = {}) ⇒ true|false

Does this model exist in a table?

User.exists?('713') # => true

If a range key is declared it should be specified in the following way:

User.exists?([['713', 'range-key-value']]) # => true

It’s possible to check existence of several models at once:

User.exists?(['713', '714', '715'])

Or in case when a range key is declared:

User.exists?(
  [
    ['713', 'range-key-value-1'],
    ['714', 'range-key-value-2'],
    ['715', 'range-key-value-3']
  ]
)

It’s also possible to specify models not with primary key but with conditions on the attributes (in the where method style):

User.exists?(age: 20, 'created_at.gt': Time.now - 1.day)

Parameters:

  • id_or_conditions (String|Array[String]|Array[Array]|Hash) (defaults to: {})

    the primary id of the model, a list of primary ids or a hash with the options to filter from.

Returns:

  • (true|false)

Since:

  • 0.2.0



150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/dynamoid/document.rb', line 150

def exists?(id_or_conditions = {})
  case id_or_conditions
  when Hash then where(id_or_conditions).count >= 1
  else
    begin
      find(id_or_conditions)
      true
    rescue Dynamoid::Errors::RecordNotFound
      false
    end
  end
end