Method: Mongoid::Findable#find_by

Defined in:
lib/mongoid/findable.rb

#find_by(attrs = {}) {|result| ... } ⇒ Document?

Find the first Document given the conditions. If a matching Document is not found and Mongoid.raise_not_found_error is true it raises Mongoid::Errors::DocumentNotFound, return null nil elsewise.

and Mongoid.raise_not_found_error is true.

Examples:

Find the document by attribute other than id

Person.find_by(:username => "superuser")

Parameters:

  • attrs (Hash) (defaults to: {})

    The attributes to check.

Yields:

  • (result)

Returns:

  • (Document, nil)

    A matching document.

Raises:

Since:

  • 3.0.0


112
113
114
115
116
117
118
119
# File 'lib/mongoid/findable.rb', line 112

def find_by(attrs = {})
  result = where(attrs).find_first
  if result.nil? && Mongoid.raise_not_found_error
    raise(Errors::DocumentNotFound.new(self, attrs))
  end
  yield(result) if result && block_given?
  result
end