@@ -253,3 +253,56 @@ either normal setting or through the build and create methods on the association
253
253
254
254
rect = Rectangle.new(width: 100, height: 200)
255
255
firefox.shapes
256
+
257
+
258
+ .. _inheritance-persistence-context:
259
+
260
+ Persistence Contexts
261
+ ====================
262
+
263
+ Mongoid allows the persistence context of a subclass to be changed from the
264
+ persistence context of its parent. This means that, using the ``store_in``
265
+ method, we can store the documents of the subclasses in different collections
266
+ (as well as different databases, clients) than their parents:
267
+
268
+ .. code:: ruby
269
+
270
+ class Shape
271
+ include Mongoid::Document
272
+ store_in collection: :shapes
273
+ end
274
+
275
+ class Circle < Shape
276
+ store_in collection: :circles
277
+ end
278
+
279
+ class Square < Shape
280
+ store_in collection: :squares
281
+ end
282
+
283
+ Shape.create!
284
+ Circle.create!
285
+ Square.create!
286
+
287
+ Setting the collection on the children causes the documents for those children
288
+ to be stored in the set collection, instead of in the parent's collection:
289
+
290
+ .. code:: javascript
291
+
292
+ > db.shapes.find()
293
+ { "_id" : ObjectId("62fe9a493282a43d6b725e10"), "_type" : "Shape" }
294
+ > db.circles.find()
295
+ { "_id" : ObjectId("62fe9a493282a43d6b725e11"), "_type" : "Circle" }
296
+ > db.squares.find()
297
+ { "_id" : ObjectId("62fe9a493282a43d6b725e12"), "_type" : "Square" }
298
+
299
+ If the collection is set on some of the subclasses and not others, the subclasses
300
+ with set collections will store documents in those collections, and the
301
+ subclasses without set collections will be store documents in the parent's
302
+ collection.
303
+
304
+ .. note::
305
+
306
+ Note that changing the collection that a subclass is stored in will cause
307
+ documents of that subclass to no longer be found in the results of querying
308
+ its parent class.
0 commit comments