123456789_123456789_123456789_123456789_123456789_

Module: Mongoid::Document

Relationships & Source Files
Namespace Children
Modules:
Extension / Inclusion / Inheritance Descendants
Included In:
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
Instance Chain:
Defined in: lib/mongoid/document.rb

Overview

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

Constant Summary

Interceptable - Included

CALLBACKS

Association::Depending - Included

STRATEGIES

Association - Included

MACRO_MAPPING

Persistable - Included

LIST_OPERATIONS

Fields - Included

Boolean, IDS, INVALID_BSON_CLASSES, StringifiedSymbol, TYPE_MAPPINGS

Clients - Included

CREATE_LOCK

Changeable - Included

ATTRIBUTE_UNCHANGED

Atomic - Included

UPDATES

Composable - Included

MODULES, RESERVED_METHOD_NAMES

Class Attribute Summary

Clients::Sessions::ClassMethods - Extended

in_transaction?

This method should be used to detect whether a persistence operation is executed inside transaction or not.

Fields::ClassMethods - Extended

using_object_ids?

Convenience method for determining if we are using BSON::ObjectIds as our id.

Scopable::ClassMethods - Extended

default_scopable?

Is the class able to have the default scope applied?

Traversable::ClassMethods - Extended

hereditary?

Determines if the document is a subclass of another document.

Validatable::ClassMethods - Extended

validating_with_query?

Are we currently performing a validation that has a query?

Encryptable::ClassMethods - Extended

encrypted?

Whether the model is encrypted.

Class Method Summary

Changeable::ClassMethods - Extended

create_dirty_change_accessor

Creates the dirty change accessor.

create_dirty_change_check

Creates the dirty change check.

create_dirty_change_flag

Creates the dirty change flag.

create_dirty_default_change_check

Creates the dirty default change check.

create_dirty_methods

Generate all the dirty methods needed for the attribute.

create_dirty_previous_change

Creates the dirty change accessor.

create_dirty_previous_value_accessor

Creates the dirty change previous value accessors.

create_dirty_previously_changed?

Creates the dirty change check.

create_dirty_reset

Creates the dirty change reset.

create_dirty_reset_to_default

Creates the dirty change reset to default.

Clients::Sessions::ClassMethods - Extended

after_commit

Sets up a callback is called after a commit of a transaction.

after_create_commit

Shortcut for after_commit :hook, on: :create.

after_destroy_commit

Shortcut for after_commit :hook, on: :destroy.

after_rollback

This callback is called after a create, update, or destroy are rolled back.

after_save_commit

Shortcut for after_commit :hook, on: [ :create, :update ].

after_update_commit

Shortcut for after_commit :hook, on: :update.

transaction

Executes a block within the context of a transaction.

with_session

Execute a block within the context of a session.

_session,
abort_transaction

Aborts the active transaction on the session, and calls after_rollback callbacks on modified documents.

assert_valid_transaction_action

Asserts that the given actions are valid for after_commit and after_rollback callbacks.

commit_transaction

Commits the active transaction on the session, and calls after_commit callbacks on modified documents.

set_options_for_callbacks!

Transforms custom options for after_commit and after_rollback callbacks into options for set_callback.

transaction_include_any_action?,
transactions_not_supported_exceptions

Driver version 2.20 introduced a new exception for reporting that transactions are not supported.

Clients::Options::ClassMethods - Extended

client_name

Get the database client name for the current persistence context of the document class.

collection

Get the collection for the current persistence context of the document class.

collection_name

Get the collection name for the current persistence context of the document class.

database_name

Get the database name for the current persistence context of the document class.

mongo_client

Get the client for the current persistence context of the document class.

persistence_context

Get the current persistence context of the document class.

with

Change the persistence context for this class during the block.

Clients::StorageOptions::ClassMethods - Extended

reset_storage_options!

Reset the store_in options.

storage_options_defaults

Get the default storage options.

store_in

Give this model specific custom default storage options.

CollectionConfigurable::ClassMethods - Extended

create_collection

Create the collection for the called upon ::Mongoid model.

Attributes::ClassMethods - Extended

alias_attribute

Alias the provided name to the original field.

unalias_attribute

Removes a field alias.

Attributes::Readonly::ClassMethods - Extended

attr_readonly

Defines an attribute as readonly.

Attributes::Nested::ClassMethods - Extended

accepts_nested_attributes_for

Used when needing to update related models from a parent association.

autosave_nested_attributes

Add the autosave information for the nested association.

Fields::ClassMethods - Extended

attribute_names

Returns an array of names for the attributes available on this object.

cleanse_localized_field_names

Removes the _translations from the given field name.

database_field_name

Get the name of the provided field as it is stored in the database.

extract_id_field

Extracts the id field from the specified attributes hash based on aliases defined in this class.

field

Defines all the fields that are accessible on the Document For each field that is defined, a getter and setter will be added as an instance method to the Document.

id_fields

Returns the list of id fields for this model class, as both strings and symbols.

replace_field

Replace a field with a new type.

traverse_association_tree

Traverse down the association tree and search for the field for the given key.

Indexable::ClassMethods - Extended

add_indexes

Add the default indexes to the root document if they do not already exist.

create_indexes

Send the actual index creation comments to the MongoDB driver.

index

Adds an index definition for the provided single or compound keys.

index_specification

Get an index specification for the provided key.

remove_indexes

Send the actual index removal comments to the MongoDB driver, but lets _id untouched.

index_keys

Gets a list of index specification keys.

indexed_database_names

Get the names of all databases for this model that have index definitions.

Persistable::Destroyable::ClassMethods - Extended

destroy_all

Delete all documents given the supplied conditions.

Persistable::Deletable::ClassMethods - Extended

delete_all

Delete all documents given the supplied conditions.

Persistable::Creatable::ClassMethods - Extended

create

Create a new document.

create!

Create a new document.

Association::Reflections::ClassMethods - Extended

reflect_on_all_associations

Returns all association metadata for the supplied macros.

reflect_on_association

Returns the association metadata for the supplied name.

Association::Macros::ClassMethods - Extended

belongs_to

Adds a referenced association from the child Document to a Document in another database or collection.

embedded_in

Adds the association back to the parent document.

embeds_many

Adds the association from a parent document to its children.

embeds_one

Adds the association from a parent document to its child.

has_and_belongs_to_many

Adds a referenced many-to-many association between many of this Document and many of another Document.

has_many

Adds a referenced association from a parent Document to many Documents in another database or collection.

has_one

Adds a referenced association from the child Document to a Document in another database or collection.

define_association!

Association::Referenced::Syncable::ClassMethods - Extended

_synced

::Set up the syncing of many to many foreign keys.

synced_destroy

::Set up the sync of inverse keys that needs to happen on a destroy.

synced_save

::Set up the sync of inverse keys that needs to happen on a save.

Association::Referenced::CounterCache::ClassMethods - Extended

decrement_counter

Decrement the counter name from the entries that match the id by one.

increment_counter

Increment the counter name from the entries that match the id by one.

reset_counters

Reset the given counter using the .count() query from the db.

update_counters

Update the given counters by the value factor.

Association::Embedded::Cyclic::ClassMethods - Extended

recursively_embeds_many

Create a cyclic embedded association that creates a tree hierarchy for the document and many embedded child documents.

recursively_embeds_one

Create a cyclic embedded association that creates a single self referencing relationship for a parent and a single child.

cyclic_child_name

Determines the child name given the class.

cyclic_parent_name

Determines the parent name given the class.

Scopable::ClassMethods - Extended

criteria
default_scope

Add a default scope to the model.

queryable

Get a queryable, either the last one on the scope stack or a fresh one.

scope

Create a scope that can be accessed from the class level or chained to criteria by the provided name.

scoped

Get a criteria for the document with normal scoping.

scopes

Returns a hash of all the scopes defined for this class, including scopes defined on ancestor classes.

unscoped

Get the criteria without any scoping applied.

with_default_scope

Get a criteria with the default scope applied, if possible.

with_scope

Pushes the provided criteria onto the scope stack, and removes it after the provided block is yielded.

without_default_scope

Execute the block without applying the default scope.

check_scope_name

Warns or raises exception if overriding another scope or method.

check_scope_validity

Checks if the intended scope is a valid object, either a criteria or proc with a criteria.

define_scope_method

Defines the actual class method that will execute the scope when called.

process_default_scope

Process the default scope value.

SearchIndexable::ClassMethods - Extended

create_search_indexes

Request the creation of all registered search indices.

remove_search_index

Removes the search index specified by the given name or id.

remove_search_indexes

Request the removal of all registered search indexes.

search_index

Adds an index definition for the provided single or compound keys.

search_indexes

A convenience method for querying the search indexes available on the current model’s collection.

wait_for_search_indexes

Waits for the named search indexes to be created.

get_indexes

Retrieves the index records for the indexes with the given names.

Shardable::ClassMethods - Extended

shard_key

Specifies a shard key with the field(s) specified.

Threaded::Lifecycle::ClassMethods - Extended

_creating

Execute a block in creating mode.

Traversable::ClassMethods - Extended

inherited

When inheriting, we want to copy the fields from the parent class and set the on the child to start, mimicking the behavior of the old class_inheritable_accessor that was deprecated in ::Rails edge.

Validatable::ClassMethods - Extended

validates_relation

Adds an associated validator for the association if the validate option was not provided or set to true.

validates_with

Add validation with the supplied validators for the provided fields with options.

Equality::ClassMethods - Extended

===

Performs class equality checking.

Encryptable::ClassMethods - Extended

encrypt_with

::Set the encryption metadata for the model.

set_key_id

Override the key_id for the model.

Instance Attribute Summary

Touchable::InstanceMethods - Included

#_touchable_parent?

Indicates whether the parent exists and is touchable.

#touch_callbacks_suppressed?

Queries whether touch callbacks are being suppressed for the class that includes this module.

Composable - Included

Changeable - Included

#changed

Get the changed attributes for the document.

#changed?

Has the document changed?

#children_changed?

Have any children (embedded documents) of this document changed?

Clients::Options - Included

#persistence_context

Get the document’s current persistence context.

#persistence_context?

Returns whether a persistence context is set for the document or the document’s class.

Clients::StorageOptions - Included

#remembered_storage_options

Remembers the storage options that were active when the current object was instantiated/created.

Attributes - Included

Fields - Included

#using_object_ids?

Is the document using object ids?

Persistable - Included

#executing_atomically?

Are we executing an atomically block on the current document?

Association - Included

#_association, #aliased_associations, #aliased_associations?, #cyclic, #cyclic?, #dependents, #dependents?, #dependents_owner, #dependents_owner?,
#embedded?

Determine if the document itself is embedded in another document via the proper channels.

#embedded_many?

Determine if the document is part of an embeds_many association.

#embedded_one?

Determine if the document is part of an embeds_one association.

#embedded_relations, #embedded_relations?,
#referenced_many?

Determine if the document is part of an references_many association.

#referenced_one?

Determine if the document is part of an references_one association.

#relations, #relations?, #stored_as_associations, #stored_as_associations?

Association::Accessors - Included

#without_autobuild?

Is the current code executing without autobuild functionality?

Association::Referenced::AutoSave - Included

#autosaved?

Used to prevent infinite loops in associated autosaves.

Stateful - Included

#_destroy
#destroyed=,
#destroyed?

Returns true if the Document has been succesfully destroyed, and false if it hasn’t.

#flagged_for_destroy=,
#flagged_for_destroy?

Returns whether or not the document has been flagged for deletion, but not destroyed yet.

#marked_for_destruction?
#new_record=

Sets whether the document has been persisted to the database.

#new_record?

Returns true if the document has not been persisted to the database, false if it has.

#persisted?

Checks if the document has been saved to the database.

#previously_new_record=,
#previously_new_record?

Returns true if this document was just created – that is, prior to the last save, the object didn’t exist in the database and new_record? would have returned true.

#previously_persisted?

Checks if the document was previously saved to the database but now it has been deleted.

#pushable?

Determine if the document can be pushed.

#readonly?

Is the document readonly?

#settable?

Determine if the document can be set.

#updateable?

Is the document updateable?

Threaded::Lifecycle - Included

#_assigning

Begin the assignment of attributes.

#_assigning?

Is the current thread in assigning mode?

#_binding

Execute a block in binding mode.

#_binding?

Is the current thread in binding mode?

#_building

Execute a block in building mode.

#_building?

Is the current thread in building mode?

#_creating?

Is the current thread in creating mode?

#_loading

Execute a block in loading mode.

#_loading?

Is the current thread in loading mode?

Traversable - Included

#_parent

Retrieves the parent document of this document.

#_parent=

Sets the parent document of this document.

#_root

Return the root document in the object graph.

#_root?

Is this document the root document of the hierarchy?

#hereditary?

Determines if the document is a subclass of another document.

Validatable - Included

#validated?

Used to prevent infinite loops in associated validations.

#validating_with_query?

Are we currently performing a validation that has a query?

Interceptable - Included

#pending_callbacks

Returns the stored callbacks to be executed later.

#pending_callbacks=

Stores callbacks to be executed later.

#before_callback_halted?

We need to hook into this for autosave, since we don’t want it firing if the before callbacks were halted.

Instance Method Summary

Touchable::InstanceMethods - Included

#_clear_touch_updates

Clears changes for the model caused by touch operation.

#_gather_touch_updates

Recursively sets touchable fields on the current document and each of its parents, including the root node.

#_run_touch_callbacks_from_root

Recursively runs :touch callbacks for the document and its parents, beginning with the root document and cascading through each successive child document.

#suppress_touch_callbacks

Suppresses the invocation of touch callbacks, for the class that includes this module, for the duration of the block.

#touch

Touch the document, in effect updating its updated_at timestamp and optionally the provided field to the current time.

#_extract_touches_from_atomic_sets

Extract and remove the atomic updates for the touch operation(s) from the currently enqueued atomic $set operations.

Atomic - Included

#_updates
#add_atomic_pull

Add the document as an atomic pull.

#add_atomic_unset

Add an atomic unset for the document.

#atomic_array_add_to_sets

For array fields these are the unique adds that need to happen.

#atomic_array_pulls

For array fields these are the pulls that need to happen.

#atomic_array_pushes

For array fields these are the pushes that need to happen.

#atomic_attribute_name

Returns path of the attribute for modification.

#atomic_delete_modifier

Get the removal modifier for the document.

#atomic_insert_modifier

Get the insertion modifier for the document.

#atomic_path

Return the path to this Document in JSON notation, used for atomic updates via $set in MongoDB.

#atomic_paths

Get the atomic paths utility for this document.

#atomic_position

Returns the positional operator of this document for modification.

#atomic_pulls

Get all the attributes that need to be pulled.

#atomic_pushes

Get all the push attributes that need to occur.

#atomic_sets

Get all the attributes that need to be set.

#atomic_unsets

Get all the attributes that need to be unset.

#atomic_updates

Get all the atomic updates that need to happen for the current Document.

#delayed_atomic_pulls

Get a hash of atomic pulls that are pending.

#delayed_atomic_sets

Get all the atomic sets that have had their saves delayed.

#delayed_atomic_unsets

Get the delayed atomic unsets.

#flag_as_destroyed

Flag the document as destroyed and return the atomic path.

#flagged_destroys

Get the flagged destroys.

#process_flagged_destroys

Process all the pending flagged destroys from nested attributes.

#generate_atomic_updates

Generates the atomic updates in the correct order.

#reset_atomic_updates!

Clears all pending atomic updates.

Changeable - Included

#attribute_before_last_save

Returns the original value of an attribute before the last save.

#attribute_changed?

Determine if a specific attribute has changed.

#attribute_changed_from_default?

Get whether or not the field has a different value from the default.

#attribute_previously_was

Get the previous attribute value that was changed before the document was saved.

#attribute_was

Get the previous value for the attribute.

#attribute_will_change!

Flag an attribute as going to change.

#changed_attributes

Get the attribute changes.

#changes

Get all the changes for the document.

#move_changes

Call this method after save, so the changes can be properly switched.

#post_persist

Things that need to execute after a document has been persisted.

#previous_changes

Get the previous changes on the document.

#remove_change

Remove a change from the dirty attributes hash.

#reset_attribute!

::Set the attribute back to its old value.

#reset_attribute_to_default!, #reset_attributes_before_type_cast,
#saved_change_to_attribute

Returns the change to an attribute during the last save.

#saved_change_to_attribute?

Returns whether this attribute changed during the last save.

#setters

Gets all the new values for each of the changed fields, to be passed to a MongoDB $set modifier.

#will_save_change_to_attribute?

Returns whether this attribute change the next time we save.

#attribute_change

Get the old and new value for the provided attribute.

#attributes_before_last_save, #changes_before_last_save,
#previous_attributes

Get attributes of the document before the document was saved.

Clients::Sessions - Included

#ensure_client_compatibility!

If at least one session is active, this ensures that the current model’s client is compatible with one of them.

Clients::Options - Included

#collection

Get the collection for the document’s current persistence context.

#collection_name

Get the collection name for the document’s current persistence context.

#mongo_client

Get the database client for the document’s current persistence context.

#with

Change the persistence context for this object during the block.

#clear_persistence_context, #set_persistence_context

Clients::StorageOptions - Included

#remember_storage_options!

Saves the storage options from the current persistence context.

#storage_options

The storage options that apply to this record, consisting of both the class-level declared storage options (e.g.

Attributes - Included

#[]
#[]=
#assign_attributes

Allows you to set all the attributes for a particular mass-assignment security role by passing in a hash of attributes with keys matching the attribute names (which again matches the column names) and the role name using the :as option.

#attribute_missing?

Determine if the attribute is missing from the document, due to loading it from the database with missing fields.

#attribute_present?

Determine if an attribute is present.

#attributes,
#attributes=
#attributes_before_type_cast

Get the attributes that have not been cast.

#has_attribute?

Does the document have the provided attribute?

#has_attribute_before_type_cast?

Does the document have the provided attribute before it was assigned and type cast?

#process_raw_attribute

Process the raw attribute values just read from the documents attributes.

#read_attribute

Read a value from the document attributes.

#read_attribute_before_type_cast

Read a value from the attributes before type cast.

#remove_attribute

Remove a value from the Document attributes.

#typed_attributes

Return type-casted attributes.

#write_attribute

Write a single attribute to the document attribute hash.

#write_attributes

Writes the supplied attributes hash to the document.

#hash_dot_syntax?

Does the string contain dot syntax for accessing hashes?

#lookup_attribute_presence, #read_raw_attribute,
#typed_value_for

Return the typecasted value for a field.

Attributes::Readonly - Included

#attribute_writable?

Are we able to write the attribute with the provided name?

#_loaded?, #as_writable_attribute!, #projected_field?

Attributes::Processing - Included

#process_attributes

Process the provided attributes casting them to their proper values if a field exists for them on the document.

#pending_attribute?

If the key provided is the name of an association or a nested attribute, we need to wait until all other attributes are set before processing these.

#pending_nested

Get all the pending nested attributes that need to be set.

#pending_relations

Get all the pending associations that need to be set.

#process_attribute

If the attribute is dynamic, add a field for it with a type of object and then either way set the value.

#process_nested

Process all the pending nested attributes that needed to wait until ids were set to fire off.

#process_pending

Process all the pending items, then clear them out.

#process_relations

Process all the pending associations that needed to wait until ids were set to fire off.

#set_pending_nested

::Set value of the pending nested attribute.

#set_pending_relation

::Set value of the pending relation.

Evolvable - Included

#__evolve_object_id__

Evolve the document into an object id.

Fields - Included

#apply_default

Applies a single default value for the given name.

#apply_defaults

Apply all the defaults at once.

#apply_post_processed_defaults

Apply all default values to the document which are procs.

#apply_pre_processed_defaults

Apply all default values to the document which are not procs.

#attribute_names

Returns an array of names for the attributes available on this object.

#database_field_name

Get the name of the provided field as it is stored in the database.

#dot_dollar_field?

Does this field start with a dollar sign ($) or contain a dot/period (.)?

#lazy_settable?

Is the provided field a lazy evaluation?

#validate_writable_field_name!

Validate whether or not the field starts with a dollar sign ($) or contains a dot/period (.).

Inspectable - Included

#inspect

Returns the class name plus its attributes.

#inspect_dynamic_fields

Get an array of inspected dynamic fields for the document.

#inspect_fields

Get an array of inspected fields for the document.

Matchable - Included

#_matches?

Determines if this document has the attributes to match the supplied MongoDB selector.

Persistable - Included

#atomically

Execute operations atomically (in a single database call) for everything that would happen inside the block.

#fail_due_to_callback!

Raise an error if a callback failed.

#fail_due_to_validation!

Raise an error if validation failed.

#_mongoid_atomic_context_changed_fields

Return the current atomic context’s changed fields.

#_mongoid_pop_atomic_context

Pop an atomic context off the stack.

#_mongoid_push_atomic_context

Push a new atomic context onto the stack.

#_mongoid_remove_atomic_context_changes

Remove the dirty changes for all fields changed in the current atomic context.

#_mongoid_reset_atomic_context_changes!

Reset the attributes for all fields changed in the current atomic context.

#persist_atomic_operations

Persist the atomic operations.

#persist_or_delay_atomic_operation

If we are in an atomically block, add the operations to the delayed group, otherwise persist immediately.

#post_process_persist

Post process the persistence operation.

#prepare_atomic_operation

Prepare an atomic persistence operation.

#process_atomic_operations

Process the atomic operations - this handles the common behavior of iterating through each op, getting the aliased field name, and removing appropriate dirty changes.

Persistable::Unsettable - Included

#unset

Perform an $unset operation on the provided fields and in the values in the document in memory.

Persistable::Upsertable - Included

#upsert

Perform an upsert of the document.

#prepare_upsert

Prepare the upsert for execution.

Persistable::Updatable - Included

#update

Update the document attributes in the database.

#update!

Update the document attributes in the database and raise an error if validation failed.

#update_attribute

Update a single attribute and persist the entire document.

#update_attributes
#update_attributes!
#enforce_immutability_of_id_field!

Checks to see if the _id field has been modified.

#init_atomic_updates

Initialize the atomic updates.

#prepare_update

Prepare the update for execution.

#process_touch_option

If there is a touch option and it is false, this method will call the timeless method so that the updated_at attribute is not updated.

#run_all_callbacks_for_update

Consolidates all the callback invocations into a single place, to avoid cluttering the logic in #prepare_update.

#update_document

Update the document in the database.

Persistable::Settable - Included

#set

Perform a $set operation on the provided field/value pairs and set the values in the document in memory.

Persistable::Savable - Included

#save

Save the document - will perform an insert if the document is new, and update if not.

#save!

Save the document - will perform an insert if the document is new, and update if not.

Persistable::Renamable - Included

#rename

Rename fields from one value to another via $rename.

Persistable::Pushable - Included

#add_to_set

Add the single values to the arrays only if the value does not already exist in the array.

#push

Push a single value or multiple values onto arrays.

Persistable::Pullable - Included

#pull

Pull single values from the provided arrays.

#pull_all

Pull multiple values from the provided array fields.

Positional - Included

#positionally

Takes the provided selector and atomic operations and replaces the indexes of the embedded documents with the positional operator when needed.

#process_operations, #process_updates, #replace_index

Persistable::Poppable - Included

#pop

Pop or shift items from arrays using the $pop operator.

Persistable::Multipliable - Included

#mul

Multiply the provided fields by the corresponding values.

Persistable::Minable - Included

#clamp_upper_bound
#set_min

::Set the given field or fields to the smaller of either it’s current value, or a given value.

Persistable::Maxable - Included

#clamp_lower_bound
#set_max

::Set the given field or fields to the larger of either it’s current value, or a given value.

Persistable::Logical - Included

#bit

Performs an atomic $bit operation on the field with the provided hash of bitwise ops to execute in order.

Persistable::Incrementable - Included

#inc

Increment the provided fields by the corresponding values.

Persistable::Destroyable - Included

#destroy

Remove the document from the database with callbacks.

#destroy!

Remove the document from the database with callbacks.

Persistable::Deletable - Included

#delete

Remove the document from the database.

#remove
#atomic_deletes

Get the atomic deletes for the operation.

#delete_as_embedded

Delete the embedded document.

#delete_as_root

Delete the root document.

#notifying_parent?

Are we needing to notify the parent document of the deletion.

#prepare_delete

Prepare the delete operation.

Persistable::Creatable - Included

#insert

Insert a new document into the database.

#atomic_inserts

Get the atomic insert for embedded documents, either a push or set.

#insert_as_embedded

Insert the embedded document.

#insert_as_root

Insert the root document.

#post_process_insert

Post process an insert, which sets the new record attribute to false and flags all the children as persisted.

#prepare_insert

Prepare the insert for execution.

Association - Included

#association_name

Get the association name for this document.

#reload_relations

Convenience method for iterating through the loaded associations and reloading them.

Association::Reflections - Included

#reflect_on_all_association

Returns all association metadata for the supplied macros.

#reflect_on_association

Returns the association metadata for the supplied name.

Association::Macros - Included

#associations

This is convenience for libraries still on the old API.

Association::Builders - Included

#parse_args

Parse out the attributes and the options from the args passed to a build_ or create_ methods.

Association::Depending - Included

Association::Accessors - Included

#__build__

Builds the related document and creates the association unless the document is nil, then sets the association on this document.

#create_relation

Create an association from an object and association metadata.

#reset_relation_criteria

Resets the criteria inside the association proxy.

#set_relation

::Set the supplied association to an instance variable on the class with the provided name.

#_mongoid_filter_selected_fields

Returns a subset of __selected_fields attribute applicable to the (embedded) association with the given key, or nil if no projection is to be performed.

#get_relation

Get the association.

#needs_no_database_query?,
#parse_args

Parse out the attributes and the options from the args passed to a build_ or create_ methods.

#without_autobuild

Yield to the block with autobuild functionality turned off.

Association::Referenced::Syncable - Included

#_syncable?

Is the document able to be synced on the inverse side? This is only if the key has changed and the association bindings have not been run.

#_synced

Get the synced foreign keys.

#_synced?

Has the document been synced for the foreign key?

#remove_inverse_keys

Update the inverse keys on destroy.

#update_inverse_keys

Update the inverse keys for the association.

Association::Referenced::CounterCache - Included

#reset_counters

Reset the given counter using the .count() query from the db.

Association::Referenced::AutoSave - Included

#__autosaving__

Begin the associated autosave.

#changed_for_autosave?

Check if there is changes for auto-saving.

Reloadable - Included

#reload

Reloads the Document attributes from the database.

#_reload

Reload the document, determining if it’s embedded or not and what behavior to use.

#check_for_deleted_document!

Checks to see if the given attributes argument indicates that the object has been deleted.

#reload_embedded_document

Reload the embedded document.

#reload_root_document

Reload the root document.

#reset_object!

Resets the current object using the given attributes.

Scopable - Included

#apply_default_scoping

Apply the default scoping to the attributes of the document, as long as they are not complex queries.

Selectable - Included

#atomic_selector

Get the atomic selector for the document.

#embedded_atomic_selector

Get the atomic selector for an embedded document.

#root_atomic_selector_in_db

Get the atomic selector that would match the existing version of the root document.

Serializable - Included

#serializable_hash

Gets the document as a serializable hash, used by ActiveModel’s JSON serializer.

#field_names

Get the names of all fields that will be serialized.

#relation_names

Since the inclusions can be a hash, symbol, or array of symbols, this is provided as a convenience to parse out the names.

#relation_options

Since the inclusions can be a hash, symbol, or array of symbols, this is provided as a convenience to parse out the options.

#serialize_attribute

Serialize a single attribute.

#serialize_relations

For each of the provided include options, get the association needed and provide it in the hash.

Shardable - Included

#shard_key_field_value

Returns the value for the named shard key.

#shard_key_fields

Get the shard key fields.

#shard_key_selector

Returns the selector that would match the defined shard keys.

#shard_key_selector_in_db

Returns the selector that would match the existing version of this document in the database.

Stateful - Included

#readonly!

Flags the document as readonly.

#reset_readonly

Cacheable - Included

#cache_key

Print out the cache key.

Traversable - Included

#_children

Get all child Documents to this Document.

#_descendants

Get all descendant Documents of this Document recursively.

#_reset_memoized_descendants!

Resets the memoized descendants on the object.

#collect_children

Collect all the children of this document.

#collect_descendants

Collect all the descendants of this document.

#flag_descendants_persisted

Marks all descendants as being persisted.

#parentize

Sets up a child/parent association.

#remove_child

Remove a child document from this parent.

#reset_persisted_descendants

After descendants are persisted we can call this to move all their changes and flag them as persisted in one call.

Validatable::Macros - Included

#validates_associated

Validates whether or not an association is valid or not.

#validates_format_of

Validates the format of a field.

#validates_length_of

Validates the length of a field.

#validates_presence_of

Validates whether or not a field is present - meaning nil or empty.

#validates_uniqueness_of

Validates whether or not a field is unique against the documents in the database.

Validatable - Included

#begin_validate

Begin the associated validation.

#exit_validate

Exit the associated validation.

#performing_validations?

Given the provided options, are we performing validations?

#read_attribute_for_validation

Overrides the default ActiveModel behavior since we need to handle validations of associations slightly different than just calling the getter.

#valid?

Determine if the document is valid.

#validating

Perform a validation within the associated block.

Interceptable - Included

#_mongoid_run_child_after_callbacks

Execute the after callbacks.

#_mongoid_run_child_before_callbacks

Execute the before callbacks of given kind for embedded documents.

#_mongoid_run_child_callbacks

Run the callbacks for embedded documents.

#_mongoid_run_child_callbacks_with_around

Execute the callbacks of given kind for embedded documents including around callbacks.

#_mongoid_run_child_callbacks_without_around

Execute the callbacks of given kind for embedded documents without around callbacks.

#callback_executable?

Is the provided type of callback executable by this document?

#in_callback_state?

Is the document currently in a state that could potentially require callbacks to be executed?

#run_after_callbacks

Run only the after callbacks for the specific event.

#run_before_callbacks

Run only the before callbacks for the specific event.

#run_callbacks

Run the callbacks for the document.

#run_pending_callbacks

Run the pending callbacks.

#cascadable_child?

Determine if the child should fire the callback.

#cascadable_children

Get all the child embedded documents that are flagged as cascadable.

#child_callback_type

Get the name of the callback that the child should fire.

#compile_callbacks

Compile the callback chain.

#halted_callback_hook

We need to hook into this for autosave, since we don’t want it firing if the before callbacks were halted.

#run_targeted_callbacks

Run only the callbacks for the target location (before, after, around) and kind (save, update, create).

Copyable - Included

#clone

Clone or dup the current Document.

#dup

Alias for Copyable#clone.

#clone_document

Clone the document attributes.

#process_localized_attributes

When cloning, if the document has localized fields we need to ensure they are properly processed in the clone.

Equality - Included

#<=>

Default comparison is via the string version of the id.

#==

Performs equality checking on the document ids.

#eql?

Delegates to ==.

DSL Calls

included

[ GitHub ]


32
33
34
# File 'lib/mongoid/document.rb', line 32

included do
  Mongoid.register_model(self)
end

Instance Attribute Details

#__selected_fields (rw)

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 29

attr_accessor :__selected_fields

#frozen?true | false (readonly)

Checks if the document is frozen

Examples:

Check if frozen

document.frozen?

Returns:

  • (true | false)

    True if frozen, else false.

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 59

def frozen?
  attributes.frozen?
end

#internal_stateHash (rw, private)

Constructs a hash representing the internal state of this object, suitable for passing to #internal_state=.

Returns:

  • (Hash)

    the map of internal state values

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 308

def internal_state
  {
    id: _id,
    changed_attributes: changed_attributes,
    errors: errors,
    new_record: new_record?,
    destroyed: destroyed?,
    discriminator_key_was: self.class.discriminator_value
  }
end

#internal_state=(state) (rw)

This method is for internal use only.

Sets the internal state of this document. Used only by #becomes to help initialize a retyped document.

Parameters:

  • state (Hash)

    The map of internal state values.

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 164

def internal_state=(state)
  self._id = state[:id]
  @changed_attributes = state[:changed_attributes]
  @errors = ActiveModel::Errors.new(self).tap { |e| e.copy!(state[:errors]) }
  @new_record = state[:new_record]
  @destroyed = state[:destroyed]

  update_discriminator(state[:discriminator_key_was])

  mark_persisted_state_for_embedded_documents(state[:new_record])
end

#new_record (readonly)

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 30

attr_reader :new_record

Instance Method Details

#_handle_callbacks_after_instantiation(execute_callbacks)

This method is for internal use only.

Handles the setup and execution of callbacks, if callbacks are to be executed; otherwise, adds the appropriate callbacks to the pending callbacks list.

Parameters:

  • execute_callbacks (true | false)

    Whether callbacks should be executed or not.

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 184

def _handle_callbacks_after_instantiation(execute_callbacks)
  if execute_callbacks
    apply_defaults
    yield self if block_given?
    run_callbacks(:find) unless _find_callbacks.empty?
    run_callbacks(:initialize) unless _initialize_callbacks.empty?
  else
    yield self if block_given?
    self.pending_callbacks += %i[ apply_defaults find initialize ]
  end
end

#add_attributes_for_relation(name, meta) (private)

Adds the attributes for the given relation to the document’s attributes.

Parameters:

  • name (String | Symbol)

    the name of the relation to add

  • meta (Mongoid::Assocation::Relatable)

    the relation object

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 281

def add_attributes_for_relation(name, meta)
  relation, stored = send(name), meta.store_as
  return unless attributes.key?(stored) || !relation.blank?

  if relation.nil?
    attributes.delete(stored)
  else
    attributes[stored] = relation.send(:as_attributes)
  end
end

#as_attributesHash (private)

Returns a hash of the attributes.

Note this method modifies the attributes hash that already exists on the class and returns it. This means that the hash returned by this method refers to the same hash as calling #attributes on the instance. See MONGOID-4476 for an explanation on how this is used.

Returns:

  • (Hash)

    The attributes hash.

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 265

def as_attributes
  return attributes if frozen?

  embedded_relations.each_pair do |name, meta|
    without_autobuild do
      add_attributes_for_relation(name, meta)
    end
  end

  attributes
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.

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 134

def as_document
  BSON::Document.new(as_attributes)
end

#becomes(klass) ⇒ Document

Returns an instance of the specified class with the attributes, errors, and embedded documents of the current document.

Examples:

Return a subclass document as a superclass instance.

manager.becomes(Person)

Parameters:

  • klass (Class)

    The class to become.

Returns:

  • (Document)

    An instance of the specified class.

Raises:

  • (ArgumentError)

    If the class doesn’t include Document

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 149

def becomes(klass)
  mongoid_document_check!(klass)

  became = klass.new(clone_document)
  became.internal_state = internal_state

  became
end

#construct_document(attrs = nil, options = {}) ⇒ Document (private)

This method is for internal use only.
Note:

A Ruby 2.x bug prevents the options hash from being keyword arguments. Once we drop support for Ruby 2.x, we can reimplement the options hash as keyword arguments. See bugs.ruby-lang.org/issues/15753

Does the construction of a document.

Parameters:

  • attrs (Hash) (defaults to: nil)

    The attributes to set up the document with.

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

    The options to use.

Options Hash (options):

  • :execute_callbacks (true | false)

    Flag specifies whether callbacks should be run.

Returns:

  • (Document)

    A new document.

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 214

def construct_document(attrs = nil, options = {})
  execute_callbacks = options.fetch(:execute_callbacks, Threaded.execute_callbacks?)

  self._parent = nil
  _building do
    prepare_to_process_attributes

    process_attributes(attrs) do
      yield(self) if block_given?
    end
    @attributes_before_type_cast = @attributes.merge(attributes_before_type_cast)

    resolve_post_construction_callbacks(execute_callbacks)
  end
  self
end

#freezeDocument

Freezes the internal attributes of the document.

Examples:

Freeze the document

document.freeze

Returns:

  • (Document)

    The document.

[ GitHub ]

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

def freeze
  as_attributes.freeze and self
end

#hashInteger

Delegates to identity in order to allow two records of the same identity 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 identity.

[ GitHub ]

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

def hash
  identity.hash
end

#identityArray

A Document’s is identified absolutely by its class and database id:

Person.first.identity #=> [Person, BSON::ObjectId(‘4f775130a04745933a000003’)]

Examples:

Get the identity

document.identity

Returns:

  • (Array)

    An array containing [document.class, document._id]

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 85

def identity
  [ self.class, _id ]
end

#initialize(attrs = nil, &block) ⇒ 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:

  • (Document)

    A new document.

[ GitHub ]

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

def initialize(attrs = nil, &block)
  construct_document(attrs, &block)
end

#loggerLogger (private)

Returns the logger

Returns:

  • (Logger)

    The configured logger or a default Logger instance.

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 243

def logger
  Mongoid.logger
end

#mark_persisted_state_for_embedded_documents(new_record) (private)

Marks all embedded documents with the given “new_record” state.

Parameters:

  • new_record (true | false)

    whether or not the embedded records should be flagged as new records or not.

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 332

def mark_persisted_state_for_embedded_documents(new_record)
  embedded_relations.each_pair do |name, _meta|
    without_autobuild do
      relation = __send__(name)
      Array.wrap(relation).each do |r|
        r.instance_variable_set(:@new_record, new_record)
      end
    end
  end
end

#model_keyString (private)

Get the name of the model used in caching.

Examples:

Get the model key.

model.model_key

Returns:

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 253

def model_key
  @model_key ||= self.class.model_name.cache_key
end

#model_nameString

Return the model name of the document.

Examples:

Return the model name.

document.model_name

Returns:

  • (String)

    The model name.

[ GitHub ]

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

def model_name
  self.class.model_name
end

#mongoid_document_check!(klass) (private)

Checks that the given argument is an instance of ‘Mongoid::Document`.

Parameters:

  • klass (Class)

    The class to test.

Raises:

  • (ArgumentError)

    if the class does not include Document.

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 298

def mongoid_document_check!(klass)
  return if klass.include?(Mongoid::Document)

  raise ArgumentError, 'A class which includes Mongoid::Document is expected'
end

#prepare_to_process_attributes (private)

Initializes the object state prior to attribute processing; this is called only from #construct_document.

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 233

def prepare_to_process_attributes
  @new_record = true
  @attributes ||= {}
  apply_pre_processed_defaults
  apply_default_scoping
end

#resolve_post_construction_callbacks(execute_callbacks) (private)

Either executes or enqueues the post-construction callbacks.

Parameters:

  • execute_callbacks (true | false)

    whether the callbacks should be executed (true) or enqueued (false)

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 347

def resolve_post_construction_callbacks(execute_callbacks)
  if execute_callbacks
    apply_post_processed_defaults
    run_callbacks(:initialize) unless _initialize_callbacks.empty?
  else
    pending_callbacks << :apply_post_processed_defaults
    pending_callbacks << :initialize
  end
end

#to_keyString

Return the key value for the document.

Examples:

Return the key.

document.to_key

Returns:

  • (String)

    The id of the document or nil if new.

[ GitHub ]

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

def to_key
  (persisted? || destroyed?) ? [ _id.to_s ] : nil
end

#update_discriminator(key_was) (private)

Updates the value of the discriminator_key for this object, setting its previous value to ‘key_was`.

Parameters:

  • key_was (String)

    the previous value of the discriminator key.

[ GitHub ]

  
# File 'lib/mongoid/document.rb', line 323

def update_discriminator(key_was)
  changed_attributes[self.class.discriminator_key] = key_was
  self[self.class.discriminator_key] = self.class.discriminator_value
end