Method: ActiveModel::Datastore::ClassMethods#find_by

Defined in:
lib/active_model/datastore.rb

#find_by(args) ⇒ Model?

Finds the first entity matching the specified condition.

Examples:

User.find_by(name: 'Joe')
User.find_by(name: 'Bryce', ancestor: parent_key)

Parameters:

  • args (Hash)

    In which the key is the property and the value is the value to look for.

Options Hash (args):

  • :ancestor (Google::Cloud::Datastore::Key)

    filter for inherited results

Returns:

  • (Model, nil)

    An ActiveModel object or nil.



340
341
342
343
344
345
346
347
# File 'lib/active_model/datastore.rb', line 340

def find_by(args)
  query = CloudDatastore.dataset.query name
  query.ancestor(args[:ancestor]) if args[:ancestor]
  query.limit(1)
  query.where(args.keys[0].to_s, '=', args.values[0])
  query_results = retry_on_exception { CloudDatastore.dataset.run query }
  from_entity(query_results.first)
end