Module: Mongoid::Document

Extended by:
ActiveSupport::Concern
Includes:
Components, MultiDatabase
Defined in:
lib/mongoid/document.rb,
lib/mongoid/railties/document.rb

Overview

This is the base module for all domain objects that need to be persisted to the database as documents.

Defined Under Namespace

Modules: ClassMethods

Constant Summary

Constants included from Callbacks

Callbacks::CALLBACKS

Constants included from Copyable

Copyable::COPYABLES

Instance Attribute Summary

Attributes included from Validations

#validated

Instance Method Summary collapse

Methods included from Validations

#read_attribute_for_validation, #valid?, #validated?

Methods included from State

#destroyed=, #destroyed?, #new_record=, #new_record?, #persisted?

Methods included from Sharding

#shard_key_selector

Methods included from Serialization

#serializable_hash

Methods included from Safety

#safely

Methods included from Relations

#embedded?, #embedded_many?, #embedded_one?, #referenced_many?, #referenced_one?

Methods included from Relations::Cascading

#cascade!

Methods included from Relations::Accessors

#build, #create_relation, #options, #relation_exists?, #set, #substitute

Methods included from Persistence

#destroy, #insert, #remove, #save!, #update, #update_attribute, #update_attributes, #update_attributes!, #upsert

Methods included from Persistence::Atomic

#add_to_set, #inc, #pull_all, #push

Methods included from Paths

#_inserter, #_path, #_position, #_remover, #_selector

Methods included from Matchers

#matches?

Methods included from Inspection

#inspect

Methods included from Dirty

#attribute_change, #attribute_changed?, #attribute_was, #changed, #changed?, #changes, #move_changes, #previous_changes, #reset_attribute!, #reset_modifications, #setters, #setup_modifications

Methods included from Attributes

#attribute_present?, #read_attribute, #remove_attribute, #respond_to?, #write_attribute, #write_attributes

Methods included from Attributes::Processing

#process

Methods included from Atomicity

#_updates

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Mongoid::Attributes

Instance Method Details

#<=>(other) ⇒ Integer

Default comparison is via the string version of the id.

Examples:

Compare two documents.

person <=> other_person

Parameters:

  • other (Document)

    The document to compare with.

Returns:



23
24
25
# File 'lib/mongoid/document.rb', line 23

def <=>(other)
  raw_attributes["_id"].to_s <=> other.raw_attributes["_id"].to_s
end

#==(other) ⇒ true, false

Performs equality checking on the document ids. For more robust equality checking please override this method.

Examples:

Compare for equality.

document == other

Parameters:

Returns:

  • (true, false)

    True if the ids are equal, false if not.



36
37
38
39
# File 'lib/mongoid/document.rb', line 36

def ==(other)
  self.class == other.class &&
    raw_attributes["_id"] == other.raw_attributes["_id"]
end

#===(other) ⇒ true, false

Performs class equality checking.

Examples:

Compare the classes.

document === other

Parameters:

Returns:

  • (true, false)

    True if the classes are equal, false if not.



49
50
51
# File 'lib/mongoid/document.rb', line 49

def ===(other)
  self.class == other.class
end

#_destroyObject

Used in conjunction with fields_for to build a form element for the destruction of this association. Always returns false because Mongoid only supports immediate deletion of associations.

See ActionView::Helpers::FormHelper::fields_for for more info.



8
9
10
# File 'lib/mongoid/railties/document.rb', line 8

def _destroy
  false
end

#as_documentHash

Return a hash of the entire document hierarchy from this document and below. Used when the attributes are needed for everything and not just the current document.

Examples:

Get the full hierarchy.

person.as_document

Returns:

  • (Hash)

    A hash of all attributes in the hierarchy.



222
223
224
225
226
227
228
229
230
# File 'lib/mongoid/document.rb', line 222

def as_document
  attributes = raw_attributes
  attributes.tap do |attrs|
    relations.select { |name, meta| meta.embedded? }.each do |name, meta|
      relation = send(name, false, :continue => false)
      attrs[name] = relation.as_document unless relation.blank?
    end
  end
end

#attributesHashWithIndifferentAccess

Return the attributes hash with indifferent access. Used mostly for convenience - use Document#raw_attributes where you dont care if the keys are all strings.

Examples:

Get the attributes.

person.attributes

Returns:

  • (HashWithIndifferentAccess)

    The attributes.



112
113
114
# File 'lib/mongoid/document.rb', line 112

def attributes
  raw_attributes.with_indifferent_access
end

#eql?(other) ⇒ true, false

Delegates to ==. Used when needing checks in hashes.

Examples:

Perform equality checking.

document.eql?(other)

Parameters:

Returns:

  • (true, false)

    True if equal, false if not.



61
62
63
# File 'lib/mongoid/document.rb', line 61

def eql?(other)
  self == (other)
end

#freezeDocument

Freezes the internal attributes of the document.

Examples:

Freeze the document

document.freeze

Returns:

Since:

  • 2.0.0



73
74
75
76
# File 'lib/mongoid/document.rb', line 73

def freeze
  raw_attributes.freeze
  self
end

#frozen?true, false

Checks if the document is frozen

Examples:

Check if frozen

document.frozen?

Returns:

  • (true, false)

    True if frozen, else false.

Since:

  • 2.0.0



86
87
88
# File 'lib/mongoid/document.rb', line 86

def frozen?
  raw_attributes.frozen?
end

#hashInteger

Delegates to id in order to allow two records of the same type and id to work with something like:

[ Person.find(1), Person.find(2), Person.find(3) ] &
[ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]

Examples:

Get the hash.

document.hash

Returns:

  • (Integer)

    The hash of the document’s id.



100
101
102
# File 'lib/mongoid/document.rb', line 100

def hash
  raw_attributes["_id"].hash
end

#identifyBSON::ObjectId, String

Generate an id for this Document.

Examples:

Create the id.

person.identify

Returns:



122
123
124
# File 'lib/mongoid/document.rb', line 122

def identify
  Identity.new(self).create
end

#initialize(attrs = nil) ⇒ Document

Instantiate a new Document, setting the Document’s attributes if given. If no attributes are provided, they will be initialized with an empty Hash.

If a primary key is defined, the document’s id will be set to that key, otherwise it will be set to a fresh BSON::ObjectId string.

Examples:

Create a new document.

Person.new(:title => "Sir")

Parameters:

  • attrs (Hash) (defaults to: nil)

    The attributes to set up the document with.

Returns:



139
140
141
142
143
144
145
146
147
# File 'lib/mongoid/document.rb', line 139

def initialize(attrs = nil)
  @new_record = true
  @attributes = apply_default_attributes
  process(attrs) do |document|
    yield self if block_given?
    identify
  end
  run_callbacks(:initialize) { self }
end

#raw_attributesHash

Return the attributes hash.

Examples:

Get the untouched attributes.

person.raw_attributes

Returns:

  • (Hash)

    This document’s attributes.



155
156
157
# File 'lib/mongoid/document.rb', line 155

def raw_attributes
  @attributes
end

#reloadDocument

Reloads the Document attributes from the database. If the document has not been saved then an error will get raised if the configuration option was set.

Examples:

Reload the document.

person.reload

Returns:

  • (Document)

    The document, reloaded.

Raises:



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/mongoid/document.rb', line 169

def reload
  reloaded = collection.find_one(:_id => id)
  if Mongoid.raise_not_found_error
    raise Errors::DocumentNotFound.new(self.class, id) if reloaded.nil?
  end
  @attributes = {}.merge(reloaded || {})
  apply_default_attributes
  reset_modifications
  tap do
    relations.keys.each do |name|
      if instance_variable_defined?("@#{name}")
        remove_instance_variable("@#{name}")
      end
    end
  end
end

#remove_child(child) ⇒ Object

Remove a child document from this parent. If an embeds one then set to nil, otherwise remove from the embeds many.

This is called from the RemoveEmbedded persistence command.

Examples:

Remove the child.

document.remove_child(child)

Parameters:

  • child (Document)

    The child (embedded) document to remove.



195
196
197
198
199
200
201
202
# File 'lib/mongoid/document.rb', line 195

def remove_child(child)
  name = child..name
  if child.embedded_one?
    remove_instance_variable("@#{name}") if instance_variable_defined?("@#{name}")
  else
    send(name).delete(child)
  end
end

#to_aArray<Document>

Return an array with this Document only in it.

Examples:

Return the document in an array.

document.to_a

Returns:

  • (Array<Document>)

    An array with the document as its only item.



210
211
212
# File 'lib/mongoid/document.rb', line 210

def to_a
  [ self ]
end