123456789_123456789_123456789_123456789_123456789_

Sessions

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:

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.

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.

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