mongodb/mongoid

View on GitHub
docs/reference/sessions.txt

Summary

Maintainability
Test Coverage
.. _sessions:

********
Sessions
********

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 2
   :class: singlecol

You can use sessions with Mongoid in a similar way that you would execute a transaction in ActiveRecord.
Namely, you can call a method, ``#with_session`` on a model class or on an instance of a model and execute
some operations in a block. All operations in the block will be executed in the context of single session.
Please see the MongoDB Ruby driver documentation for what session options are available.

Please note the following limitations of sessions:

- Sessions cannot be shared across threads; sessions are not thread-safe. This is consistent with the Ruby driver's support for sessions.

- Sessions cannot be nested. You cannot called ``#with_session`` on a model class or a model instance within the block passed to the ``#with_session`` method on another model class or model instance.

- All model classes and instances used within the session block must use the same driver client. For example, if you have specified different ``storage_options`` for another model used in the block than that of the model class or instance on which ``#with_session`` is called, you will get an error.

Using a Session via Model#with_session
======================================

Call ``#with_session`` on a model class and pass it session options to execute a block in the context
of a session.

.. code-block:: ruby

   Person.with_session(causal_consistency: true) do
     Person.create!
     person = Person.first
     person.name = "Emily"
     person.save
   end


Using a Session via model#with_session
======================================

Call ``#with_session`` on a model instance and pass it session options to execute a block in the context
of a session.

.. code-block:: ruby

   person.with_session(causal_consistency: true) do
     person.username = 'Emily'
     person.save
     person.posts << Post.create!
   end