-
Notifications
You must be signed in to change notification settings - Fork 21
/
README.html
1602 lines (1579 loc) · 176 KB
/
README.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<h1 id="mongoid-relations-and-queries">Mongoid Relations and Queries</h1>
<p>This document describes the highlights and assembly of the <code>Movies</code> application using a Mongoid-based backend. Much of the emphasis is placed on the data-tier and the controller, while leaving the view minimally integrated. This is to keep the focus on the data tier.</p>
<p>You will find the following topics discussed in this module:</p>
<ul>
<li>Model classes</li>
<li>Relationships
<ul>
<li>Embedded</li>
<li>Linked</li>
</ul></li>
<li>Queries</li>
<li>Geolocation</li>
<li>Indexes, etc.</li>
</ul>
<h2 id="highlights">Highlights</h2>
<h3 id="initialization">Initialization</h3>
<p>This section quickly covers the highlights relative to getting started. All cooked data is located within <code>db/*.json</code> and can be easily imported using the <code>rake</code> shell command.</p>
<ol style="list-style-type: decimal">
<li><p>Run <code>bundle</code> to ensure the necessary gems are installed</p></li>
<li><p>(In a separate terminal) Start the MongoDB server using <code>mongod</code></p></li>
<li><p>Import the data using <code>rake db:seed</code> to create all collections. This will execute the code within <code>db/seed.rb</code> and use the JSON data also located in the <code>db/</code> directory.</p>
<pre class="shell"><code>$ rake db:seed
adding places
adding actors
adding writers
adding directors
adding movies</code></pre></li>
<li><p>Add required indexes to the collections using rake <code>db:mongoid:create_indexes</code>. The source of these indexes are located within the associated Mongoid model classes in the <code>app/model</code> directory.</p>
<pre class="shell"><code>$ rake db:mongoid:create_indexes
D, [2015-11-30T17:26:06.796020 #34396] DEBUG -- : MONGODB | Adding localhost:27017 to the cluster.
D, [2015-11-30T17:26:06.837599 #34396] DEBUG -- : MONGODB | localhost:27017 | movies_development.createIndexes | STARTED | {"createIndexes"=>"actors", "indexes"=>[{:key=>{:"place_of_birth.geolocation"=>"2dsphere"}, :name=>"place_of_birth.geolocation_2dsphere"}]}
D, [2015-11-30T17:26:06.873807 #34396] DEBUG -- : MONGODB | localhost:27017 | movies_development.createIndexes | SUCCEEDED | 0.036063000000000005s</code></pre></li>
</ol>
<p>One of the indexes created is a <code>2dsphere</code> index on the <code>place_of_birth.geolocation</code> property of an <code>Actor</code>.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Actor</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
embeds_one <span class="st">:place_of_birth</span>, as: <span class="st">:locatable</span>, class_name: <span class="st">'Place'</span>
...
index ({ :<span class="st">"place_of_birth.geolocation"</span> => <span class="dt">Mongo</span>::<span class="dt">Index</span>::<span class="dt">GEO2DSPHERE</span> })
...
<span class="kw">end</span></code></pre>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id=</span>><span class="st">"nm0543215"</span>,
<span class="st">:name=</span>><span class="st">"Sarah Manninen"</span>,
<span class="st">:place_of_birth=</span>>
{<span class="st">:_id=</span>><span class="st">"Pasadena, CA, USA"</span>,
<span class="st">:geolocation=</span>>{<span class="st">:type=</span>><span class="st">"Point"</span>, <span class="st">:coordinates=</span>>[-<span class="fl">118.1445155</span>, <span class="fl">34.1477849</span>]},
<span class="st">:city=</span>><span class="st">"Pasadena"</span>,
<span class="st">:county=</span>><span class="st">"Los Angeles County"</span>,
<span class="st">:state=</span>><span class="st">"CA"</span>,
<span class="st">:country=</span>><span class="st">"US"</span>}}</code></pre>
<h3 id="model-types-and-document-representation">Model Types and Document Representation</h3>
<p>This section describes the individual document and custom types contained within the example. Documents have <code>_id</code> properties. Custom types are anonymous compound data structures embedded within documents.</p>
<h3 id="measurement-custom-type">Measurement (Custom Type)</h3>
<p><code>Measurement</code> is an example of a custom type. Instead of modeling a property with just the <code>amount</code> (60) or a compound label with "amount (units)" ("60 min"), we have chosen to create a compound data structure with <code>amount</code> and <code>units</code>.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="st">:runtime=</span>>{<span class="st">:amount=</span>><span class="dv">60</span>, <span class="st">:units=</span>><span class="st">"min"</span>}</code></pre>
<p>The entire class has been supplied here for the first example of a custom class. All other custom classes have a similar concept to:</p>
<ul>
<li>provide an initialize method that is marshaling format independent</li>
<li>provide one (1) instance method called <code>mongoize</code> required by Mongoid that will marshal the state of the instance into database form.</li>
<li>provide three (3) class methods to:
<ul>
<li>transform any form of the object into database form (<code>mongoize</code>)</li>
<li>create an object instance from database form (<code>demongoize</code>)</li>
<li>support various other transformations required by the criteria queries (<code>evolve</code>).</li>
</ul></li>
</ul>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Measurement</span>
<span class="ot">attr_reader</span> <span class="st">:amount</span>, <span class="st">:units</span>
<span class="kw">def</span> initialize(amount, units=<span class="dv">nil</span>)
<span class="ot">@amount</span>=amount
<span class="ot">@units</span> = units
<span class="co">#normalize</span>
<span class="kw">case</span>
<span class="kw">when</span> <span class="ot">@units</span> == <span class="st">"meters"</span> <span class="kw">then</span> <span class="ot">@amount</span>=(<span class="ot">@amount</span>/<span class="fl">0.3048</span>); <span class="ot">@units</span>=<span class="st">"feet"</span>
<span class="kw">end</span>
<span class="kw">end</span>
<span class="co">#creates a DB-form of the instance</span>
<span class="kw">def</span> mongoize
<span class="ot">@units</span> ? {<span class="st">:amount</span> => <span class="ot">@amount</span>, <span class="st">:units</span> => <span class="ot">@units</span>} : {<span class="st">:amount</span> => <span class="ot">@amount</span>}
<span class="kw">end</span>
<span class="co">#creates an instance of the class from the DB-form of the data</span>
<span class="kw">def</span> <span class="dv">self</span>.demongoize(object)
<span class="dt">Measurement</span>.new(object[<span class="st">:amount</span>], object[<span class="st">:units</span>])
<span class="kw">end</span>
<span class="co">#takes in all forms of the object and produces a DB-friendly form</span>
<span class="kw">def</span> <span class="dv">self</span>.mongoize(object)
<span class="kw">case</span> object
<span class="kw">when</span> <span class="dt">Measurement</span> <span class="kw">then</span> object.mongoize
<span class="kw">else</span> object
<span class="kw">end</span>
<span class="kw">end</span>
<span class="co">#used by criteria to convert object to DB-friendly form</span>
<span class="kw">def</span> evolve(object)
<span class="kw">case</span> object
<span class="kw">when</span> <span class="dt">Measurement</span> <span class="kw">then</span> object.mongoize
<span class="kw">else</span> object
<span class="kw">end</span>
<span class="kw">end</span>
<span class="kw">end</span></code></pre>
<h3 id="point-custom-type">Point (Custom Type)</h3>
<p><code>Point</code> is a custom class that represents a geolocation point. It marshals itself in <a href="http://geojson.org/geojson-spec.html"><code>GeoJSON Point</code></a> format, but is used to read in other formats commonly found. The coordinates array is in the order of [<code>longitude</code>, <code>latitude</code>]. The inner workings of the class function much like the <code>Measurement</code> custom type.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:type=</span>><span class="st">"Point"</span>, <span class="st">:coordinates=</span>>[-<span class="fl">118.1445155</span>, <span class="fl">34.1477849</span>]},</code></pre>
<h3 id="place-document-model-class">Place (Document Model Class)</h3>
<p><code>Place</code> is an abstraction added to <code>Point</code> to hold location information about the gelocation point. It commonly contains official address information reported by the <a href="https://developers.google.com/maps/documentation/geocoding/intro"><code>Google Maps Geocoding API</code></a>.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id=</span>><span class="st">"Pasadena, CA, USA"</span>,
<span class="st">:geolocation=</span>>{<span class="st">"type"</span>=><span class="st">"Point"</span>, <span class="st">"coordinates"</span>=>[-<span class="fl">118.1445155</span>, <span class="fl">34.1477849</span>]},
<span class="st">:city=</span>><span class="st">"Pasadena"</span>,
<span class="st">:county=</span>><span class="st">"Los Angeles County"</span>,
<span class="st">:state=</span>><span class="st">"CA"</span>,
<span class="st">:country=</span>><span class="st">"US"</span>}</code></pre>
<p>A few things to point out about this model class</p>
<ul>
<li><code>_id</code> is mapped to <code>formatted_address</code></li>
<li>the <code>geolocation</code> property uses a custom type (<code>Point</code>)</li>
<li>although you will find this document type embedded within other documents, it exists as a stand-alone document within its own <code>places</code> collection.</li>
<li>more details about this class will be shown in the relationships section below.</li>
<li>stating the field type is not required by Mongoid, but Mongoid will test for type if supplied. A few of the attributes have had their type removed just to demonstrate they are optional.</li>
</ul>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Place</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:_id</span>, type: <span class="dt">String</span>, default: -> { formatted_address }
field <span class="st">:formatted_address</span>, type: <span class="dt">String</span>
field <span class="st">:geolocation</span>, type: <span class="dt">Point</span>
field <span class="st">:street_number</span>
field <span class="st">:street_name</span>
field <span class="st">:city</span>
field <span class="st">:postal_code</span>, type: <span class="dt">String</span>
field <span class="st">:county</span>, type: <span class="dt">String</span>
field <span class="st">:state</span>, type: <span class="dt">String</span>
field <span class="st">:country</span>, type: <span class="dt">String</span>
...
<span class="kw">end</span></code></pre>
<h3 id="actor">Actor</h3>
<p><code>Actor</code> is a document model class that represents someone who plays a role in a <code>Movie</code>. They are independent of any one movie -- thus a candidate to stand-alone in their own collection and be referenced. The information in this model class is unique to the <code>Actor</code>.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id"=>"</span>nm0993498<span class="st">",</span>
<span class="st"> :bio=> "</span><span class="dt">Arisa</span> <span class="dt">Cox</span> was born on <span class="dt">December</span> <span class="dv">7</span>, <span class="dv">1978</span> <span class="kw">in</span> <span class="dt">Toronto</span>, ...
<span class="st">:birthName=</span>><span class="st">"Arisa Natalie Cox"</span>,
<span class="st">:name=</span>><span class="st">"Arisa Cox"</span>,
<span class="st">:urlPhoto=</span>> <span class="st">"http://ia.media-imdb.com/images/M/MV5BM...7_AL_.jpg"</span>,
<span class="st">:date_of_birth=</span>><span class="dv">1978-12</span><span class="bn">-07</span> <span class="dv">00</span>:<span class="dv">00</span>:<span class="dv">00</span> <span class="dt">UTC</span>,
<span class="st">:place_of_birth=</span>> ... (see <span class="dv">1</span>:<span class="dv">1</span> embedded relationship example)</code></pre>
<p>A few things to point out about this model class</p>
<ul>
<li>although not necessary since the names match the default choice -- the instances of <code>Actor</code> will be stored in the <code>actors</code> collection.</li>
<li><code>created_at</code> and <code>updated_at</code> fields can be added and managed by Mongoid with the addition of the <code>Timestamps</code> mixin. This will be demonstrated later.</li>
<li>The camelCase <code>birthName</code> from the document is mapped to the snake_case <code>birth_name</code> in the model class. This becomes important if you compress your JSON names or are simply trying to comply with Rails naming conventions for model property names (a good thing to do).</li>
<li><code>date_of_birth</code> has been represented as a <code>Date</code> type instead of a string representation of the date</li>
<li><code>height</code> is represented as a custom type (<code>Measurement</code>)</li>
<li>more details about this class will be shown in the relationships section below.</li>
</ul>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Actor</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
<span class="co"># include Mongoid::Timestamps</span>
store_in collection: <span class="st">"actors"</span>
field <span class="st">:name</span>, type: <span class="dt">String</span>
field <span class="st">:birthName</span>, as: <span class="st">:birth_name</span>, type: <span class="dt">String</span>
field <span class="st">:date_of_birth</span>, type: <span class="dt">Date</span>
field <span class="st">:height</span>, type: <span class="dt">Measurement</span>
field <span class="st">:bio</span>, type: <span class="dt">String</span>
... (see relationships <span class="kw">for</span> additional details)
<span class="kw">end</span></code></pre>
<p>One thing to note is that by moving our schema away from being UI display/String-based, we have introduced a complexity for the UI to make non-String updates. An attempt to map many of the String to data type conversions has been inserted into the examples, but there clearly are additional data type conversions to consider when you see the full end-to-end interactions.</p>
<p>Notice that both the phiscal document key and the model class alias key can be used when inspecting the model instance. In the following case, we are still able to access the raw <code>birthName</code> in the document, in addition to the mapped <code>birth_name</code> in the class.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> <span class="dt">Actor</span>.find(<span class="st">"nm0993498"</span>).birth_name
=> <span class="st">"Arisa Natalie Cox"</span>
> <span class="dt">Actor</span>.find(<span class="st">"nm0993498"</span>).birthName
=> <span class="st">"Arisa Natalie Cox"</span></code></pre>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id=</span>><span class="st">"nm0993498"</span>,
<span class="st">:birthName=</span>><span class="st">"Arisa Natalie Cox"</span>,</code></pre>
<h3 id="writer">Writer</h3>
<p><code>Writer</code> is one of the authors of a <code>Movie</code> and, like <code>Actor</code>, stored in a separate collection. The example does not include enough data to warrant a separate collection, but we are going to pretend that is true. One thing to note is that <code>Writer</code> has no refined role within a Movie -- so it will be referenced directly from the <code>Movie</code> document.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id=</span>><span class="st">"nm0905152"</span>, <span class="st">:name=</span>><span class="st">"Andy Wachowski"</span> ... (please imagine more properties) }</code></pre>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Writer</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:name</span>, type: <span class="dt">String</span>
...
<span class="kw">end</span></code></pre>
<h3 id="director">Director</h3>
<p><code>Director</code> is one of the directors of a <code>Movie</code> and, like <code>Writer</code>, requires some imagination on your part that we have enough data here to warrant a separate collection for the <code>Director</code>.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id=</span>><span class="st">"nm0001081"</span>, <span class="st">:name=</span>><span class="st">"Cameron Crowe"</span> ... (please imagine more properties) } </code></pre>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Director</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:name</span>, type: <span class="dt">String</span>
<span class="kw">end</span></code></pre>
<h3 id="directorref">DirectorRef</h3>
<p><code>DirectorRef</code> is an annotated reference to a <code>Director</code>. It will be used to cache stable/core director information that the referencing document/view normally cares about and then contains a link to the details of the <code>Director</code> (where you are asked to use your imagination that more details exist).</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:name=</span>><span class="st">"F.W. Murnau"</span>, <span class="st">:_id=</span>><span class="st">"nm0003638"</span>}</code></pre>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">DirectorRef</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:name</span>, type: <span class="dt">String</span>
<span class="kw">end</span></code></pre>
<h3 id="movierole">MovieRole</h3>
<p><code>MovieRole</code> is a character in a <code>Movie</code> played by an <code>Actor</code>. It contains descriptive information about the movie character and the id, name, and url of the actor image and profile (both just URLs). The information for this actor that is not relative to this movie or movie role (character) is located within the <code>actors</code> collection.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:actorName=</span>><span class="st">"George O'Brien"</span>,
<span class="st">:character=</span>><span class="st">"The Man"</span>,
<span class="st">:main=</span>><span class="dv">true</span>,
<span class="st">:urlCharacter=</span>><span class="st">"http://www.imdb.com/character/ch0131526"</span>,
<span class="st">:urlPhoto=</span>>
<span class="st">"http://ia.media-imdb.com/images/M/MV5BMTI2MDg3NjYx...AL_.jpg"</span>,
<span class="st">:urlProfile=</span>><span class="st">"http://www.imdb.com/name/nm0639563"</span>,
<span class="st">:_id=</span>><span class="st">"nm0639563"</span>}</code></pre>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">MovieRole</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:character</span>, type: <span class="dt">String</span>
field <span class="st">:actorName</span>, as: <span class="st">:actor_name</span>, type: <span class="dt">String</span>
field <span class="st">:main</span>, type: <span class="dt">Mongoid</span>::<span class="dt">Boolean</span>
field <span class="st">:urlCharacter</span>, as: <span class="st">:url_character</span>, type: <span class="dt">String</span>
field <span class="st">:urlPhoto</span>, as: <span class="st">:url_photo</span>, type: <span class="dt">String</span>
field <span class="st">:urlProfile</span>, as: <span class="st">:url_profile</span>, type: <span class="dt">String</span>
...
<span class="kw">end</span></code></pre>
<h3 id="movie">Movie</h3>
<p><code>Movie</code> contains core information about the <code>Movie</code> and links to other information related to the movie.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id=</span>><span class="st">"tt0018455"</span>,
<span class="st">:actors=</span>>
[{<span class="st">:actorName=</span>><span class="st">"George O'Brien"</span>,
<span class="st">:character=</span>><span class="st">"The Man"</span>,
<span class="st">:main=</span>><span class="dv">true</span>,
<span class="st">:urlCharacter=</span>><span class="st">"http://www.imdb.com/character/ch0131526"</span>,
<span class="st">:urlPhoto=</span>>
<span class="st">"http://ia.media-imdb.com/images/M/MV5BMTI2MDg3NjYx...AL_.jpg"</span>,
<span class="st">:urlProfile=</span>><span class="st">"http://www.imdb.com/name/nm0639563"</span>,
<span class="st">:_id=</span>><span class="st">"nm0639563"</span>},
...
],
<span class="st">:countries=</span>>[<span class="st">"USA"</span>],
<span class="st">:directors=</span>>[{<span class="st">:name=</span>><span class="st">"F.W. Murnau"</span>, <span class="st">:_id=</span>><span class="st">"nm0003638"</span>}],
<span class="st">:filmingLocations=</span>>
[<span class="st">"Big Bear Lake"</span>, <span class="st">"Big Bear Valley"</span>, <span class="st">"San Bernardino National Forest"</span>, <span class="st">"California"</span>, <span class="st">"USA"</span>],
<span class="st">:genres=</span>>[<span class="st">"Comedy"</span>, <span class="st">"Drama"</span>, <span class="st">"Romance"</span>],
<span class="st">:languages=</span>>[],
<span class="st">:metascore=</span>><span class="st">""</span>,
<span class="st">:originalTitle=</span>><span class="st">"Sunrise: A Song of Two Humans"</span>,
<span class="st">:plot=</span>> <span class="st">"In this fable-morality subtitled ..."</span>
<span class="st">:rated=</span>><span class="st">"NOT RATED"</span>,
<span class="st">:rating=</span>><span class="fl">8.4</span>,
<span class="st">:runtime=</span>>{<span class="st">:amount=</span>><span class="dv">94</span>, <span class="st">:units=</span>><span class="st">"min"</span>},
<span class="st">:simplePlot=</span>> <span class="st">"A married farmer falls under the spell of ...</span>
<span class="st"> :title=>"</span><span class="dt">Sunrise</span><span class="st">",</span>
<span class="st"> :type=>"</span><span class="dt">Movie</span><span class="st">",</span>
<span class="st"> :urlIMDB=>"</span>http:<span class="ot">//</span>www.imdb.com/title/tt0018455<span class="st">",</span>
<span class="st"> :urlPoster=></span>
<span class="st"> "</span>http:<span class="ot">//i</span>a.media-imdb.com/images/M/<span class="dt">MV5BMjIzNzg4</span>....<span class="dt">TE</span>@._V1_SX214_AL_.jpg<span class="st">",</span>
<span class="st"> :votes=>25165,</span>
<span class="st"> :writers=>["</span>nm0562346<span class="st">", "</span>nm0837183<span class="st">"],</span>
<span class="st"> :year=>1927,</span>
<span class="st"> :release_date=>1927-01-04 00:00:00 UTC}</span></code></pre>
<p>A few things to point out about this model class</p>
<ul>
<li><code>year</code> and <code>votes</code> are mapped as type <code>Integer</code></li>
<li><code>runtime</code> is mapped as a custom type <code>Measurement</code></li>
<li>camelCase <code>filmingLocations</code>, <code>simplePlot</code>, <code>urlIMDB</code>, and <code>urlPoster</code> names have been mapped to snake_case <code>filming_locations</code>, <code>simple_plot</code>, <code>url_IMDB</code>, and <code>url_poster</code> names.</li>
</ul>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Movie</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:title</span>, type: <span class="dt">String</span>
field <span class="st">:type</span>, type: <span class="dt">String</span>
field <span class="st">:rated</span>, type: <span class="dt">String</span>
field <span class="st">:year</span>, type: <span class="dt">Integer</span>
field <span class="st">:release_date</span>, type: <span class="dt">Date</span>
field <span class="st">:runtime</span>, type: <span class="dt">Measurement</span>
field <span class="st">:votes</span>, type: <span class="dt">Integer</span>
field <span class="st">:countries</span>, type: <span class="dt">Array</span>
field <span class="st">:languages</span>, type: <span class="dt">Array</span>
field <span class="st">:genres</span>, type: <span class="dt">Array</span>
field <span class="st">:filmingLocations</span>, as: <span class="st">:filming_locations</span>, type: <span class="dt">Array</span>
field <span class="st">:metascore</span>, type: <span class="dt">String</span>
field <span class="st">:simplePlot</span>, as: <span class="st">:simple_plot</span>, type: <span class="dt">String</span>
field <span class="st">:plot</span>, type: <span class="dt">String</span>
field <span class="st">:urlIMDB</span>, as: <span class="st">:url_IMDB</span>, type: <span class="dt">String</span>
field <span class="st">:urlPoster</span>, as: <span class="st">:url_poster</span>, type: <span class="dt">String</span>
...
<span class="kw">end</span></code></pre>
<h3 id="model-relationships-and-realization">Model Relationships and Realization</h3>
<p>This section describes additional relationship properties for the model types introduced above.</p>
<h3 id="embedded-actor---place_of_birthplace">1:1 Embedded (<code>Actor -> place_of_birth:Place</code>)</h3>
<p>The <code>Actor</code> has one (1) <code>place_of_birth</code> property with an embedded <code>Place</code>. Please note that this same <code>Place</code> instance can show up in multiple <code>Actors</code> as well as other references to this specific place. That means that access to the <code>Place</code> properties are very efficient from its parent document, but must be updated everywhere as things change. In this case it would be rare to have to update these properties unless <code>Canada</code> became part of a different country.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id=</span>><span class="st">"nm0543215"</span>,
<span class="st">:name=</span>><span class="st">"Sarah Manninen"</span>,
...
<span class="st">:date_of_birth=</span>><span class="dv">1977</span><span class="bn">-01</span><span class="dv">-20</span> <span class="dv">00</span>:<span class="dv">00</span>:<span class="dv">00</span> <span class="dt">UTC</span>,
<span class="st">:place_of_birth=</span>>
{<span class="st">:_id=</span>><span class="st">"Waterloo, ON, Canada"</span>,
<span class="st">:geolocation=</span>>{<span class="st">"type"</span>=><span class="st">"Point"</span>, <span class="st">"coordinates"</span>=>[-<span class="fl">80.5204096</span>, <span class="fl">43.4642578</span>]},
<span class="st">:city=</span>><span class="st">"Waterloo"</span>,
<span class="st">:county=</span>><span class="st">"Waterloo Regional Municipality"</span>,
<span class="st">:state=</span>><span class="st">"ON"</span>,
<span class="st">:country=</span>><span class="st">"CA"</span>}}</code></pre>
<p>The embedded <code>Place</code> declares it is <code>embedded_in</code> the parent document. In this case there are many parent document types that could have a <code>Place</code>, so we take advantage of the <code>polymorphic</code> keyword and define the parent document as a <code>:locatable</code> instead of a specific model class.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Place</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
...
embedded_in <span class="st">:locatable</span>, polymorphic: <span class="dv">true</span>
<span class="kw">end</span></code></pre>
<p>The parent document declares <code>embeds_one</code> for the embedded type. However,</p>
<ul>
<li>since the name of the embedded class (<code>Place</code>) is not the same as the reference (<code>place_of_birth</code>), an additional property of <code>class_name: 'Place'</code> is supplied.</li>
<li>since other types can also contain this embedded type, the polymorphic label of <code>locatable</code> is also supplied.</li>
</ul>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Actor</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
...
embeds_one <span class="st">:place_of_birth</span>, as: <span class="st">:locatable</span>, class_name: <span class="st">'Place'</span></code></pre>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Writer</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
...
embeds_one <span class="st">:hometown</span>, as: <span class="st">:locatable</span>, class_name: <span class="st">'Place'</span>
<span class="kw">end</span></code></pre>
<p>To demonstrate, lets locate an <code>Actor</code> that does not yet have an address listed and make up an address for their place of birth.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> actor=<span class="dt">Actor</span>.where(<span class="st">:place_of_birth=</span>>{<span class="st">:$exists=</span>><span class="dv">0</span>}).first
> pp <span class="dt">Actor</span>.collection.find(<span class="st">:_id=</span>>actor.id).first
{<span class="st">"_id"</span>=><span class="st">"nm0828941"</span>,
<span class="st">"bio"</span>=> <span class="st">"Gerda Stevenson was born in ..."</span>
<span class="st">"height"</span>=>{<span class="st">"amount"</span>=><span class="fl">5.413386</span>, <span class="st">"units"</span>=><span class="st">"feet"</span>},
<span class="st">"name"</span>=><span class="st">"Gerda Stevenson"</span>}</code></pre>
<p>Lets claim this person is from <code>Oakland</code> and get its address properties from our <code>places</code> collection.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> oakland=<span class="dt">Place</span>.where(<span class="st">:city=</span>><span class="st">"Oakland"</span>).first</code></pre>
<p>Next we use the <code>parent.create_(embedded_relation)</code> method and a copy of the <code>place</code> properties to create an embedded instance of <code>Place</code> within <code>Actor</code>.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> actor.create_place_of_birth(oakland.attributes)
> pp <span class="dt">Actor</span>.collection.find(<span class="st">:_id=</span>>actor.id).first
{<span class="st">"_id"</span>=><span class="st">"nm0828941"</span>,
<span class="st">"bio"</span>=> <span class="st">"Gerda Stevenson was born in ..."</span>
<span class="st">"height"</span>=>{<span class="st">"amount"</span>=><span class="fl">5.413386</span>, <span class="st">"units"</span>=><span class="st">"feet"</span>},
<span class="st">"name"</span>=><span class="st">"Gerda Stevenson"</span>,
<span class="st">"place_of_birth"</span>=>
{<span class="st">"_id"</span>=><span class="st">"Oakland, CA, USA"</span>,
<span class="st">"geolocation"</span>=>{<span class="st">"type"</span>=><span class="st">"Point"</span>, <span class="st">"coordinates"</span>=>[-<span class="fl">122.2711137</span>, <span class="fl">37.8043637</span>]},
<span class="st">"city"</span>=><span class="st">"Oakland"</span>,
<span class="st">"county"</span>=><span class="st">"Alameda County"</span>,
<span class="st">"state"</span>=><span class="st">"CA"</span>,
<span class="st">"country"</span>=><span class="st">"US"</span>}}</code></pre>
<p>To show we can insert another copy of the same embedded object in another collecton -- we locate a <code>Writer</code> that does not yet have a <code>hometown</code> (we changed the relation name on purpose) and place an embedded copy of <code>Oakland</code> there too.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> writer=<span class="dt">Writer</span>.where(<span class="st">:hometown=</span>>{<span class="st">:$exists=</span>><span class="dv">0</span>}).first
> pp <span class="dt">Writer</span>.collection.find(<span class="st">:_id=</span>>writer.id).first
{<span class="st">"_id"</span>=><span class="st">"nm0000230"</span>, <span class="st">"name"</span>=><span class="st">"Sylvester Stallone"</span>}
> writer.create_hometown(oakland.attributes)
> pp <span class="dt">Writer</span>.collection.find(<span class="st">:_id=</span>>writer.id).first
{<span class="st">"_id"</span>=><span class="st">"nm0000230"</span>,
<span class="st">"name"</span>=><span class="st">"Sylvester Stallone"</span>,
<span class="st">"hometown"</span>=>
{<span class="st">"_id"</span>=><span class="st">"Oakland, CA, USA"</span>,
<span class="st">"geolocation"</span>=>{<span class="st">"type"</span>=><span class="st">"Point"</span>, <span class="st">"coordinates"</span>=>[-<span class="fl">122.2711137</span>, <span class="fl">37.8043637</span>]},
<span class="st">"city"</span>=><span class="st">"Oakland"</span>,
<span class="st">"county"</span>=><span class="st">"Alameda County"</span>,
<span class="st">"state"</span>=><span class="st">"CA"</span>,
<span class="st">"country"</span>=><span class="st">"US"</span>}}</code></pre>
<p>We can inspect the <code>writer</code> object methods for other things we can do with our embedded object <code>hometown</code>.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> writer.methods.grep <span class="ot">/hometown/</span>
=> [<span class="st">:hometown</span>, <span class="st">:hometown=</span>, <span class="st">:hometown?</span>, <span class="st">:has_hometown?</span>, <span class="st">:build_hometown</span>, <span class="st">:create_hometown</span>] </code></pre>
<p>We can get the embedded object.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> writer.hometown.id
=> <span class="st">"Oakland, CA, USA"</span> </code></pre>
<p>We can inquire whether we have an instance of the hometown.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> writer.hometown?
=> <span class="dv">true</span>
> writer.has_hometown?
=> <span class="dv">true</span> </code></pre>
<p>We can build a transient instance of the embedded object.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> place=writer.build_hometown</code></pre>
<p>We can create a hollow embedded object. This still reports that the parent document has an instance of the embedded -- even though it is hollow.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> writer.create_hometown
> pp <span class="dt">Writer</span>.collection.find(<span class="st">:_id=</span>>writer.id).first
{<span class="st">"_id"</span>=><span class="st">"nm0000230"</span>, <span class="st">"name"</span>=><span class="st">"Sylvester Stallone"</span>, <span class="st">"hometown"</span>=>{}}
> writer.has_hometown?
=> <span class="dv">true</span> </code></pre>
<p>We can remove the embedded object.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> writer.hometown=<span class="dv">nil</span>
=> <span class="dv">nil</span>
> writer.has_hometown?
=> <span class="dv">false</span>
> pp <span class="dt">Writer</span>.collection.find(<span class="st">:_id=</span>>writer.id).first
{<span class="st">"_id"</span>=><span class="st">"nm0000230"</span>, <span class="st">"name"</span>=><span class="st">"Sylvester Stallone"</span>}</code></pre>
<p>But notice that simple assignment does not embed the transient association.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> writer.hometown
=> <span class="dv">nil</span>
> writer.hometown=oakland
> writer.hometown
=> <span class="co">#<Place _id: Oakland, CA, USA...</span>
> pp <span class="dt">Writer</span>.collection.find(<span class="st">:_id=</span>>writer.id).first
{<span class="st">"_id"</span>=><span class="st">"nm0000230"</span>, <span class="st">"name"</span>=><span class="st">"Sylvester Stallone"</span>}
> writer.save
=> <span class="dv">true</span>
> pp <span class="dt">Writer</span>.collection.find(<span class="st">:_id=</span>>writer.id).first
{<span class="st">"_id"</span>=><span class="st">"nm0000230"</span>, <span class="st">"name"</span>=><span class="st">"Sylvester Stallone"</span>}</code></pre>
<h3 id="m1-linked-director---residenceplace">M:1 Linked (<code>Director -> residence:Place</code>)</h3>
<p>In a M:1 relationship, the one (1) side is the parent (with a primary key) and the many (M) side is the child (with a foreign key to the parent). The child must declare a <code>belongs_to</code> property to have the foreign key stored locally to realize the relationship. The parent optionally defines a <code>has_many</code> property. In this case we actually have a M:1 uni-directional relationship. Many directors can have one (1) residence:Place and can navigate that link. However, the parent does not know about the relationship and cannot navigate in the other direction. Since <code>Place</code> is being used in different contexts differently -- we chose to keep this uni-directional and leave <code>Place</code> ignorant of what is related to it.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id=</span>><span class="st">"nm0001081"</span>,
<span class="st">:name=</span>><span class="st">"Cameron Crowe"</span>,
<span class="st">:residence_id=</span>><span class="st">"Los Angeles, CA, USA"</span>}</code></pre>
<p>Remember that <code>Place</code> uses its <code>formatted_address</code> as its <code>_id</code>. Thus the foreign key in this case actually contains useful business information even before navigating the link.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Director</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
...
belongs_to <span class="st">:residence</span>, class_name: <span class="st">'Place'</span>
<span class="kw">end</span></code></pre>
<p>To provide an example of using this relationship...locate a <code>Director</code> that does not yet have a residence.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> director=<span class="dt">Director</span>.where(<span class="st">:residence=</span>>{<span class="st">:$exists=</span>><span class="dv">0</span>}).first
=> <span class="co">#<Director _id: nm0001081, name: "Cameron Crowe", residence_id: nil> </span>
> pp <span class="dt">Director</span>.collection.find(<span class="st">:_id=</span>>director.id).first
{<span class="st">:_id=</span>><span class="st">"nm0001081"</span>, <span class="st">:name=</span>><span class="st">"Cameron Crowe"</span>}</code></pre>
<p>Assign the <code>director.residence</code> to an instance of <code>Place</code>.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> oakland=<span class="dt">Place</span>.where(<span class="st">:city=</span>><span class="st">"Oakland"</span>).first
=> <span class="co">#<Place _id: Oakland, CA, USA, > </span>
> director.residence=oakland
=> <span class="co">#<Place _id: Oakland, CA, USA, > </span></code></pre>
<p>Notice this did not immediately write anything to the database. The foreign key to the <code>Place</code> is writen when the <code>Director</code> is saved.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> pp <span class="dt">Director</span>.collection.find(<span class="st">:_id=</span>>director.id).first
{<span class="st">:_id=</span>><span class="st">"nm0001081"</span>, <span class="st">:name=</span>><span class="st">"Cameron Crowe"</span>}
=> {<span class="st">:_id=</span>><span class="st">"nm0001081"</span>, <span class="st">:name=</span>><span class="st">"Cameron Crowe"</span>}
> director.save
> pp <span class="dt">Director</span>.collection.find(<span class="st">:_id=</span>>director.id).first
{<span class="st">:_id=</span>><span class="st">"nm0001081"</span>, <span class="st">:name=</span>><span class="st">"Cameron Crowe"</span>, <span class="st">:residence_id=</span>><span class="st">"Oakland, CA, USA"</span>}</code></pre>
<p>There are many helper methods for this relationship, so I will pick out a few and shoot for some that do not overlap with the embedded ones covered earlier.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> director.methods.grep(<span class="ot">/residence/</span>).count
=> <span class="dv">17</span> </code></pre>
<p>Realize the related object is now in a separate collection and the <code>Director</code> only has a foreign key stored locally to that related document. Therefore, accessing any properties related to the <code>Place</code> causes a separate query to the database since there is no such thing as a join performed within the database within MongoDB.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> director=<span class="dt">Director</span>.find(director.id)
<span class="dt">DEBUG</span> | {<span class="st">"find"</span>=><span class="st">"directors"</span>, <span class="st">"filter"</span>=>{<span class="st">"_id"</span>=><span class="st">"nm0001081"</span>}}
=> <span class="co">#<Director _id: nm0001081, name: "Cameron Crowe", residence_id: "Oakland, CA, USA"></span>
> director.residence.state
<span class="dt">DEBUG</span> | {<span class="st">"find"</span>=><span class="st">"places"</span>, <span class="st">"filter"</span>=>{<span class="st">"_id"</span>=><span class="st">"Oakland, CA, USA"</span>}}
=> <span class="st">"CA"</span> </code></pre>
<p>However, if all you want to access is the foreign key stored in the child document, you can call <code>(relation name)_id</code> and not have to access the parent collection.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> director.residence_id
=> <span class="st">"Oakland, CA, USA</span></code></pre>
<p>If you have the foreign key for the parent document...</p>
<pre><code>> director=Director.find(director.id)
=> #<Director _id: nm0001081, name: "Cameron Crowe", residence_id: "Oakland, CA, USA">
> la_id=Place.where(:city=>"LA").first.id
=> "Los Angeles, CA, USA" </code></pre>
<p>...the assignment can be made using <code>(relation name)_id=</code> instead of getting an instance of the parent to form the relationship.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> director.residence_id=la_id
=> <span class="st">"Los Angeles, CA, USA"</span>
> director.save
> pp <span class="dt">Director</span>.collection.find(<span class="st">:_id=</span>>director.id).first
{<span class="st">:_id=</span>><span class="st">"nm0001081"</span>,
<span class="st">:name=</span>><span class="st">"Cameron Crowe"</span>,
<span class="st">:residence_id=</span>><span class="st">"Los Angeles, CA, USA"</span>}</code></pre>
<h3 id="m-embedded-movie---rolesmovierole">1:M Embedded (<code>Movie <-> roles:MovieRole</code>)</h3>
<p>For the 1:M embedded we have a single document with parent properties and multiple embedded children and the children have identities.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id=</span>><span class="st">"tt0075148"</span>,
<span class="st">:title=</span>><span class="st">"Rocky"</span>,
<span class="st">:roles=</span>>
[{<span class="st">:actorName=</span>><span class="st">"Sylvester Stallone"</span>,
<span class="st">:character=</span>><span class="st">"Rocky"</span>,
<span class="st">:main=</span>><span class="dv">true</span>,
...
<span class="st">:_id=</span>><span class="st">"nm0000230"</span>},
{<span class="st">:actorName=</span>><span class="st">"Talia Shire"</span>,
<span class="st">:character=</span>><span class="st">"Adrian"</span>,
<span class="st">:main=</span>><span class="dv">true</span>,
...
<span class="st">:_id=</span>><span class="st">"nm0001735"</span>},
...]
}</code></pre>
<p>The parent declares an <code>embeds_many</code>, listing the collection name and the <code>class_name</code> of the embedded child if it does not match the singular form of the collection name.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Movie</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:title</span>, type: <span class="dt">String</span>
...
embeds_many <span class="st">:roles</span>, class_name:<span class="st">"MovieRole"</span>
...
<span class="kw">end</span></code></pre>
<p>The child class delcares an <code>embedded_in</code>, listing the parent property. In this case the name of the property and name of the parent model class match -- so no <code>class_name</code> is necessary.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">MovieRole</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:character</span>, type: <span class="dt">String</span>
field <span class="st">:actorName</span>, as: <span class="st">:actor_name</span>, type: <span class="dt">String</span>
field <span class="st">:main</span>, type: <span class="dt">Mongoid</span>::<span class="dt">Boolean</span>
...
embedded_in <span class="st">:movie</span>
...
<span class="kw">end</span></code></pre>
<p>We can demonstrate the 1:M embedded by first creating a new <code>Movie</code>. The <code>create</code> method performs the combined function of <code>new/initialize</code> and <code>save</code> and the parent document must be saved before creating embedded objects (i.e., saving to database).</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky25=<span class="dt">Movie</span>.create(<span class="st">:_id=</span>><span class="st">"tt9000000"</span>, <span class="st">:title=</span>><span class="st">"Rocky XXV"</span>)</code></pre>
<p>We find an actor to play a role in the movie and then create that role relative to the collection. That immediately updates the parent document with the embedded role. Since this is a 1:M relationship, the role is placed within an array.</p>
<pre class="ruby."><code>> stallone=Actor.where(:name=>{:$regex=>"Stallone"}).first
> rocky=rocky25.roles.create(:_id=>stallone.id, :character=>"Rocky", :actorName=>"Sly", :main=>true)
> pp Movie.collection.find(:title=>"Rocky XXV").first
{"_id"=>"tt9000000",
"title"=>"Rocky XXV",
"roles"=>
[{"_id"=>"nm0000230",
"character"=>"Rocky",
"actorName"=>"Sly",
"main"=>true}]}</code></pre>
<p>To add a second role -- we locate another actor and fill in the details of the role using a transient instance and then add the instance to the collection. The addition to the collection immediately updates the state of the parent document.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> actor=<span class="dt">Actor</span>.first
> role=<span class="dt">MovieRole</span>.new
> role.id=actor.id
> role.character=<span class="st">"Challenger"</span>
> role.main=<span class="dv">false</span>
> role.actor_name=actor.name
> rocky25.roles << role
> pp <span class="dt">Movie</span>.collection.find(<span class="st">:title=</span>><span class="st">"Rocky XXV"</span>).first
{<span class="st">:_id=</span>><span class="st">"tt9000000"</span>,
<span class="st">:title=</span>><span class="st">"Rocky XXV"</span>,
<span class="st">:roles=</span>>
[{<span class="st">:_id=</span>><span class="st">"nm0000230"</span>, <span class="st">:character=</span>><span class="st">"Rocky"</span>, <span class="st">:actorName=</span>><span class="st">"Sly"</span>, <span class="st">:main=</span>><span class="dv">true</span>},
{<span class="st">:_id=</span>><span class="st">"nm0084430"</span>,
<span class="st">:character=</span>><span class="st">"Challenger"</span>,
<span class="st">:main=</span>><span class="dv">false</span>,
<span class="st">:actorName=</span>><span class="st">"Erwin Biswanger"</span>}]}</code></pre>
<p>We can repeat the example -- except this time form the entire parent document prior to the intial save.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky26=<span class="dt">Movie</span>.new(<span class="st">:_id=</span>><span class="st">"tt9000001"</span>, <span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>)
> rocky=rocky26.roles.build(<span class="st">:_id=</span>>stallone.id, <span class="st">:character=</span>><span class="st">"Rocky"</span>, <span class="st">:actorName=</span>><span class="st">"Sly"</span>, <span class="st">:main=</span>><span class="dv">true</span>)
> rocky26.roles << role
> pp <span class="dt">Movie</span>.collection.find(<span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>).first
<span class="dv">nil</span></code></pre>
<p>At the point we have the transient object fully formed and now will save to the database.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky26.save
=> <span class="dv">true</span>
> pp <span class="dt">Movie</span>.collection.find(<span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>).first
{<span class="st">"_id"</span>=><span class="st">"tt9000001"</span>,
<span class="st">"title"</span>=><span class="st">"Rocky XXVI"</span>,
<span class="st">"roles"</span>=>
[{<span class="st">"_id"</span>=><span class="st">"nm0000230"</span>,
<span class="st">"character"</span>=><span class="st">"Rocky"</span>,
<span class="st">"actorName"</span>=><span class="st">"Sly"</span>,
<span class="st">"main"</span>=><span class="dv">true</span>},
{<span class="st">"_id"</span>=><span class="st">"nm0084430"</span>,
<span class="st">"character"</span>=><span class="st">"Challenger"</span>,
<span class="st">"main"</span>=><span class="dv">false</span>,
<span class="st">"actorName"</span>=><span class="st">"Erwin Biswanger"</span>}]}</code></pre>
<p>Another interesting feature is that the embedded object can provide a reference to its parent document.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> role.movie.title
=> <span class="st">"Rocky XXVI"</span></code></pre>
<h3 id="m1-embedded-linked-movierole---actor">M:1 Embedded Linked (<code>MovieRole <-> Actor</code>)</h3>
<p>Although not technically an official relationship type, it is a common pattern when linking documents within MongoDB to maintain a certain amount of state about the link on the source side. This is sometimes called an <code>annotated link</code>. There are many actors in a movie, but each of those actors play a specific role that is important and specific to the movie. Elsewhere in this description you found that <code>MovieRole</code> was embedded in <code>Movie</code> to describe the role played by an <code>Actor</code>. That <code>MovieRole</code> also contained cached information about the <code>Actor</code>. We will now look at the M:1 relationship between the embedded <code>MovieRole</code> and <code>Actor</code>.</p>
<p>As described -- the one side has a primary key and typically no reference to the child within the document. That is true about the following parent document (<code>Actor</code>).</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id=</span>><span class="st">"nm0000354"</span>,
<span class="st">:birthName=</span>><span class="st">"Matthew Paige Damon"</span>,
<span class="st">:height=</span>>{<span class="st">:amount=</span>><span class="fl">5.8398952</span>, <span class="st">:units=</span>><span class="st">"feet"</span>},
<span class="st">:name=</span>><span class="st">"Matt Damon"</span>,
<span class="st">:date_of_birth=</span>><span class="dv">1970-10-08</span> <span class="dv">00</span>:<span class="dv">00</span>:<span class="dv">00</span> <span class="dt">UTC</span>,
...
<span class="st">:place_of_birth=</span>>
{<span class="st">:_id=</span>><span class="st">"Boston, MA, USA"</span>,
<span class="st">:geolocation=</span>>{<span class="st">:type=</span>><span class="st">"Point"</span>, <span class="st">:coordinates=</span>>[-<span class="fl">71.0588801</span>, <span class="fl">42.3600825</span>]},
<span class="st">:city=</span>><span class="st">"Boston"</span>,
<span class="st">:county=</span>><span class="st">"Suffolk County"</span>,
<span class="st">:state=</span>><span class="st">"MA"</span>,
<span class="st">:country=</span>><span class="st">"US"</span>}}</code></pre>
<p>The many side will typically host the foreign key. That is true with <code>MovieRole</code>, but there is some complexity in hosting the foreign key in the embedded document.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id=</span>><span class="st">"tt0440963"</span>,
<span class="st">:title=</span>><span class="st">"The Bourne Ultimatum"</span>,
...
<span class="st">:roles=</span>>
[{<span class="st">:actorName=</span>><span class="st">"Matt Damon"</span>,
<span class="st">:character=</span>><span class="st">"Jason Bourne"</span>,
<span class="st">:main=</span>><span class="dv">true</span>,
...
<span class="st">:_id=</span>><span class="st">"nm0000354"</span>},
...
}</code></pre>
<p>We are able to add the <code>belongs_to</code> relation to <code>MovieRole</code> and map that to the <code>_id</code> field (instead of the default <code>actor_id</code>).</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">MovieRole</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:character</span>, type: <span class="dt">String</span>
field <span class="st">:actorName</span>, as: <span class="st">:actor_name</span>, type: <span class="dt">String</span>
field <span class="st">:main</span>, type: <span class="dt">Mongoid</span>::<span class="dt">Boolean</span>
embedded_in <span class="st">:movie</span>
...
belongs_to <span class="st">:actor</span>, <span class="st">:foreign_key</span> => <span class="st">:_id</span>
...
<span class="kw">end</span></code></pre>
<p>However, we are unable to declare a <code>has_many</code> to an embedded class. We are forced to write some application logic and take a peek at queries. In the <code>roles</code> method below, we first search for all movies for the actor, iterate through those movie documents and implement a follow-on queuy to locate a specific role within the movie. In watching the database interactions through debug -- it actually looks like all work is done within Mongoid to locate the result of the second query.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Actor</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:name</span>, type: <span class="dt">String</span>
<span class="co">#not supported</span>
<span class="co">#has_many roles:, class_name: 'MovieRole`</span>
<span class="co">#replaced with</span>
<span class="kw">def</span> roles
<span class="dt">Movie</span>.where(:<span class="st">"roles._id"</span>=><span class="dv">self</span>.id)
.map {|m| m.roles.where(<span class="st">:_id=</span>><span class="dv">self</span>.id).first}
<span class="kw">end</span>
<span class="kw">end</span></code></pre>
<p>To demonstrate the relationship, lets locate an actor that we know should have many roles.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> damon=<span class="dt">Actor</span>.where(<span class="st">:name=</span>>{<span class="st">:$regex=</span>><span class="st">"Matt Da"</span>}).first</code></pre>
<p>We can search for a nested <code>roles._id</code> field matching the actor.id value. That gives us a list of the movies the actor has played in.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> movie=<span class="dt">Movie</span>.where(:<span class="st">"roles._id"</span>=>damon.id).first</code></pre>
<p>From there we can locate a specific role having the actor's ID and show that the role has the foreign key to the actor.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> role=movie.roles.where(<span class="st">:id=</span>>damon.id).first
> pp role.attributes
{<span class="st">:actorName=</span>><span class="st">"Matt Damon"</span>,
<span class="st">:character=</span>><span class="st">"Jason Bourne"</span>,
<span class="st">:main=</span>><span class="dv">true</span>,
...
<span class="st">:_id=</span>><span class="st">"nm0000354"</span>}</code></pre>
<p>We can bundle that query information and application logic into the following <code>roles</code> instance method to give us all roles.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"> <span class="kw">def</span> roles
<span class="dt">Movie</span>.where(:<span class="st">"roles._id"</span>=><span class="dv">self</span>.id)
.map {|m| m.roles.where(<span class="st">:_id=</span>><span class="dv">self</span>.id).first}
<span class="kw">end</span> </code></pre>
<p>With all roles, we can go from the actor to each movie.role to locate each movie and associated character they have played.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> damon.roles.map {|role| <span class="st">"</span><span class="ot">#{</span>role.movie.title<span class="ot">}</span><span class="st"> => </span><span class="ot">#{</span>role.character<span class="ot">}</span><span class="st">"</span> }
=> [<span class="st">"The Bourne Ultimatum => Jason Bourne"</span>, <span class="st">"Good Will Hunting => Will Hunting"</span>,
<span class="st">"The Martian => Mark Watney"</span>, <span class="st">"Saving Private Ryan => Private Ryan"</span>] </code></pre>
<p>In forming the relationship, lets add the actor to a fake role in a fake movie.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> damon=<span class="dt">Actor</span>.where(<span class="st">:name=</span>>{<span class="st">:$regex=</span>><span class="st">"Matt Da"</span>}).first
> rocky26=<span class="dt">Movie</span>.create(<span class="st">:_id=</span>><span class="st">"tt9000001"</span>, <span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>)
> rocky=rocky26.roles.create(<span class="st">:_id=</span>>damon.id, <span class="st">:character=</span>><span class="st">"Rocky"</span>, <span class="st">:actorName=</span>><span class="st">"Matt"</span>, <span class="st">:main=</span>><span class="dv">true</span>)
> pp <span class="dt">Movie</span>.collection.find(<span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>).first
{<span class="st">:_id=</span>><span class="st">"tt9000001"</span>,
<span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>,
<span class="st">:roles=</span>>
[{<span class="st">:_id=</span>><span class="st">"nm0000354"</span>, <span class="st">:character=</span>><span class="st">"Rocky"</span>, <span class="st">:actorName=</span>><span class="st">"Matt"</span>, <span class="st">:main=</span>><span class="dv">true</span>}]}</code></pre>
<p>Now we can go in an search for roles that are part of their newly assignment movie and return the movie <code>title</code> and <code>character</code> they will be playing.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> damon.roles.select{|role| <span class="ot">/Rocky/</span>=~role.movie.title} \
.map {|role| <span class="st">"</span><span class="ot">#{</span>role.movie.title<span class="ot">}</span><span class="st"> => </span><span class="ot">#{</span>role.character<span class="ot">}</span><span class="st">"</span> }
=> [<span class="st">"Rocky XXVI => Rocky"</span>]</code></pre>
<h3 id="linked-movie---sequel_tomovie">1:1 Linked (<code>Movie -> sequel_to:Movie</code>)</h3>
<p>The 1:1 linked relationship has the same parent/child relationship as the 1:M, except that there is only a single child. In this example we create a recursive relationship between movies where each <code>sequel</code> <code>Movie</code> contains the foreign key to its parent <code>Movie</code> it is a <code>sequel_to</code>. The child class storing the foreign key declares <code>belongs_to</code> and the parent class defines <code>has_one</code> if the relationship is bi-directional. Since neither property matches the name <code>Movie</code>, they both have to declare a <code>class_name</code> to indicate what is at the other end of the relationship.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">{<span class="st">:_id=</span>><span class="st">"tt9000000"</span>,
<span class="st">:title=</span>><span class="st">"Rocky XXV"</span>,
<span class="st">:roles=</span>> ... }
{<span class="st">:_id=</span>><span class="st">"tt9000001"</span>,
<span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>,
<span class="st">:roles=</span>> ...
<span class="st">:sequel_to_id=</span>><span class="st">"tt9000000"</span>}</code></pre>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Movie</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:title</span>, type: <span class="dt">String</span>
...
has_one <span class="st">:sequel</span>, class_name:<span class="st">"Movie"</span>
belongs_to <span class="st">:sequel_to</span>, class_name:<span class="st">"Movie"</span>
...
<span class="kw">end</span></code></pre>
<p>Using the definition above we would automatically get a foreign key document key of <code>sequel_to_id</code>. You can map that to any other field name except <code>sequel_to</code> using <code>foreign_key: :other_field_name</code>. Even when defining the <code>foreign_key: :sequel_to</code>, Mongoid will use <code>:sequel_to_id</code>. If we truely want that name to be the key in the document we can work around it by changing the model class relation name to be different from the document key.</p>
<p>To demonstrate the relationship we will locate a <code>Movie</code> and its <code>sequel</code>. The parent movie is assigned to the <code>sequel_to</code> property of the child. This updates the in-memory state of the <code>sequel</code>.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky25=<span class="dt">Movie</span>.where(<span class="st">:title=</span>><span class="st">"Rocky XXV"</span>).first
> rocky26=<span class="dt">Movie</span>.where(<span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>).first
> rocky26.sequel_to=rocky25
> pp <span class="dt">Movie</span>.collection.find(<span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>).first
{<span class="st">:_id=</span>><span class="st">"tt9000001"</span>,
<span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>,
<span class="st">:roles=</span>> ...</code></pre>
<p>The in-memory state of the sequel is written to the database during the next save. You can see the foreign key when the document is printed.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky26.save
=> <span class="dv">true</span>
> pp <span class="dt">Movie</span>.collection.find(<span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>).first
{<span class="st">:_id=</span>><span class="st">"tt9000001"</span>,
<span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>,
<span class="st">:roles=</span>> ...
<span class="st">:sequel_to_id=</span>><span class="st">"tt9000000"</span>}</code></pre>
<p>No state is written to the parent document.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> pp <span class="dt">Movie</span>.collection.find(<span class="st">:title=</span>><span class="st">"Rocky XXV"</span>).first
{<span class="st">:_id=</span>><span class="st">"tt9000000"</span>,
<span class="st">:title=</span>><span class="st">"Rocky XXV"</span>,
<span class="st">:roles=</span>> ... }</code></pre>
<p>Note that one can navigate the relationship in both directions.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky26.sequel_to.title
=> <span class="st">"Rocky XXV"</span>
> rocky26.sequel_to.sequel.title
=> <span class="st">"Rocky XXVI"</span> </code></pre>
<h3 id="mm-movie---writerswriter">M:M (<code>Movie <-> writers:Writer</code>)</h3>
<p>In a many-to-many bi-directional relationship, each side has an important primary key and the other side stores that as a foreign key in an collection. In the example, The <code>Movie</code> has primary key (<code>tt0091763</code>) and a collection of foreign keys to its <code>Writers</code> (collection with just one - <code>["nm0000231"]</code>).</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">movie:
{<span class="st">:_id=</span>><span class="st">"tt0091763"</span>, <span class="st">:title=</span>><span class="st">"Platoon"</span>, <span class="st">:writer_ids=</span>>[<span class="st">"nm0000231"</span>]}</code></pre>
<p>The <code>Writer</code> has a primary key (<code>nm0000231</code>) that matches one of the elements in the related movie. It too has a collection of foreign keys. The collection of foreign keys in the <code>Writer</code> are foreign keys to the <code>Movie</code> documents (<code>[..., "tt0091763"]</code>)</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">writer:
{<span class="st">:_id=</span>><span class="st">"nm0000231"</span>,
<span class="st">:name=</span>><span class="st">"Oliver Stone"</span>,
<span class="st">:movie_ids=</span>>[<span class="st">"tt0086250"</span>, <span class="st">"tt0091763"</span>]}</code></pre>
<p>Both sides of the relationship declare a <code>has_and_belongs_to_many</code> with the name of the relationship. The long word has two meanings; <code>has_many</code> and <code>belongs_to</code>. The <code>belongs_to</code> aspect stores the foreign key to the parent document and the <code>has_many</code> means it is the parent of many child documents. When we bring the two concepts together -- the <code>has_many</code> and <code>belongs_to</code> are both feed off the local collection of document foreign keys.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Writer</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:name</span>, type: <span class="dt">String</span>
embeds_one <span class="st">:hometown</span>, as: <span class="st">:locatable</span>, class_name: <span class="st">'Place'</span>
...
has_and_belongs_to_many <span class="st">:movies</span>
...
<span class="kw">end</span></code></pre>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Movie</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:title</span>, type: <span class="dt">String</span>
...
has_and_belongs_to_many <span class="st">:writers</span>
...
<span class="kw">end</span></code></pre>
<p>To look at our bi-directional, many-to-many relationship, we can get the movie properties by navigating a relationship from the writer.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> stone=<span class="dt">Writer</span>.where(<span class="st">:name=</span>>{<span class="st">:$regex=</span>><span class="st">"Stone"</span>}).first
> stone.movies.map {|m| m.title}
=> [<span class="st">"Scarface"</span>, <span class="st">"Platoon"</span>] </code></pre>
<p>We can also go the other way. In this example we add a <code>hometown</code> property to the writer and get the hometown through a reference from the movie.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> stone=<span class="dt">Writer</span>.where(<span class="st">:name=</span>>{<span class="st">:$regex=</span>><span class="st">"Stone"</span>}).first
> nyc=<span class="dt">Place</span>.where(<span class="st">:_id=</span>>{<span class="st">:$regex=</span>><span class="st">"^New York, NY"</span>}).first
> stone.create_hometown(nyc.attributes)
> platoon=<span class="dt">Movie</span>.where(<span class="st">:title=</span>><span class="st">"Platoon"</span>).first
> platoon.writers.first.hometown.id
=> <span class="st">"New York, NY, USA"</span> </code></pre>
<p>To demonstrate creating a many-to-many relationship, lets create a new movie which we can verify has no writers at this point.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky26=<span class="dt">Movie</span>.create(<span class="st">:_id=</span>><span class="st">"tt9000001"</span>, <span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>)
> pp <span class="dt">Movie</span>.collection.find(<span class="st">:_id=</span>>rocky26.id).first
{<span class="st">:_id=</span>><span class="st">"tt9000001"</span>, <span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>}</code></pre>
<p>Lets go out and find a writer and notice the writer has already written two movies.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> stone=<span class="dt">Writer</span>.where(<span class="st">:name=</span>>{<span class="st">:$regex=</span>><span class="st">"Stone"</span>}).first
> pp <span class="dt">Writer</span>.collection.find(<span class="st">:_id=</span>>stone.id).first
{<span class="st">:_id=</span>><span class="st">"nm0000231"</span>,
<span class="st">:name=</span>><span class="st">"Oliver Stone"</span>,
<span class="st">:movie_ids=</span>>[<span class="st">"tt0086250"</span>, <span class="st">"tt0091763"</span>]}</code></pre>
<p>Add the writer to the collection of movie writers.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky26.writers << stone
=> [<span class="co">#<Writer _id: nm0000231, name: "Oliver Stone", movie_ids: ["tt0086250", "tt0091763", "tt9000001"]>] </span></code></pre>
<p>Notice that Mongoid has updated both ends of the collection with the foreign key of the other.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> pp <span class="dt">Movie</span>.collection.find(<span class="st">:_id=</span>>rocky26.id).first
{<span class="st">:_id=</span>><span class="st">"tt9000001"</span>, <span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>, <span class="st">:writer_ids=</span>>[<span class="st">"nm0000231"</span>]}
=> {<span class="st">:_id=</span>><span class="st">"tt9000001"</span>, <span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>, <span class="st">:writer_ids=</span>>[<span class="st">"nm0000231"</span>]}
> pp <span class="dt">Writer</span>.collection.find(<span class="st">:_id=</span>>stone.id).first
{<span class="st">:_id=</span>><span class="st">"nm0000231"</span>,
<span class="st">:name=</span>><span class="st">"Oliver Stone"</span>,
<span class="st">:movie_ids=</span>>[<span class="st">"tt0086250"</span>, <span class="st">"tt0091763"</span>, <span class="st">"tt9000001"</span>]}
=> {<span class="st">:_id=</span>><span class="st">"nm0000231"</span>, <span class="st">:name=</span>><span class="st">"Oliver Stone"</span>, <span class="st">:movie_ids=</span>>[<span class="st">"tt0086250"</span>, <span class="st">"tt0091763"</span>, <span class="st">"tt9000001"</span>]} </code></pre>
<p>Great! We can use both references to locate information about the other simply by walking the relationship.</p>
<pre><code>> stone.movies.map{|m| m.title}
=> ["Scarface", "Platoon", "Rocky XXVI"]
> rocky26.writers.map{|w| w.name}
=> ["Oliver Stone"] </code></pre>
<p>Notice that when the relationship is removed from one end -- it is also removed from the other end.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> stone.movies.delete rocky26
> pp <span class="dt">Writer</span>.collection.find(<span class="st">:_id=</span>>stone.id).first
{<span class="st">:_id=</span>><span class="st">"nm0000231"</span>,
<span class="st">:name=</span>><span class="st">"Oliver Stone"</span>,
<span class="st">:movie_ids=</span>>[<span class="st">"tt0086250"</span>, <span class="st">"tt0091763"</span>]}
=> {<span class="st">:_id=</span>><span class="st">"nm0000231"</span>, <span class="st">:name=</span>><span class="st">"Oliver Stone"</span>, <span class="st">:movie_ids=</span>>[<span class="st">"tt0086250"</span>, <span class="st">"tt0091763"</span>]}
> pp <span class="dt">Movie</span>.collection.find(<span class="st">:_id=</span>>rocky26.id).first
{<span class="st">:_id=</span>><span class="st">"tt9000001"</span>, <span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>, <span class="st">:writer_ids=</span>>[]}
=> {<span class="st">:_id=</span>><span class="st">"tt9000001"</span>, <span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>, <span class="st">:writer_ids=</span>>[]} </code></pre>
<h3 id="timestamps">Timestamps</h3>
<p>Timestamp information is not added by default in Mongoid -- as it is within ActiveRecord. To add <code>created_at</code> and <code>updated_at</code> fields and management, we add an additional <code>Mongoid::Timestamps</code> mixin.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Movie</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
include <span class="dt">Mongoid</span>::<span class="dt">Timestamps</span></code></pre>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Writer</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
include <span class="dt">Mongoid</span>::<span class="dt">Timestamps</span></code></pre>
<p>Lets demonstrate the timestamp capability by re-doing the M:M relationship scenario and create our movie again with timestamps in place. Notice that two new elements have been introduced to the document for <code>created_at</code> and <code>updated_at</code>. We can also get these explicitly from the object.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky26=<span class="dt">Movie</span>.create(<span class="st">:_id=</span>><span class="st">"tt9000001"</span>, <span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>)
> pp <span class="dt">Movie</span>.collection.find(<span class="st">:_id=</span>>rocky26.id)
{<span class="st">:_id=</span>><span class="st">"tt9000001"</span>,
<span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>,
<span class="st">:updated_at=</span>><span class="dv">2015-11-28</span> <span class="dv">20</span>:<span class="dv">47</span>:<span class="dv">59</span> <span class="dt">UTC</span>,
<span class="st">:created_at=</span>><span class="dv">2015-11-28</span> <span class="dv">20</span>:<span class="dv">47</span>:<span class="dv">59</span> <span class="dt">UTC</span>}
> rocky26.created_at
=> <span class="dt">Sat</span>, <span class="dv">28</span> <span class="dt">Nov</span> <span class="dv">2015</span> <span class="dv">20</span>:<span class="dv">47</span>:<span class="dv">59</span> <span class="dt">UTC</span> +<span class="dv">00</span>:<span class="dv">00</span>
> rocky26.updated_at
=> <span class="dt">Sat</span>, <span class="dv">28</span> <span class="dt">Nov</span> <span class="dv">2015</span> <span class="dv">20</span>:<span class="dv">47</span>:<span class="dv">59</span> <span class="dt">UTC</span> +<span class="dv">00</span>:<span class="dv">00</span> </code></pre>
<p><code>updated_at</code> will be modified as the document is changed and saved.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky26.year=<span class="dv">2015</span>
=> <span class="dv">2015</span>
> rocky26.save
=> <span class="dv">true</span>
> rocky26.updated_at
=> <span class="dt">Sat</span>, <span class="dv">28</span> <span class="dt">Nov</span> <span class="dv">2015</span> <span class="dv">20</span>:<span class="dv">48</span>:<span class="dv">28</span> <span class="dt">UTC</span> +<span class="dv">00</span>:<span class="dv">00</span> </code></pre>
<p>The writer was imported prior to timestamps being configured and does not have a <code>created_at</code> and <code>updated_at</code> to start with.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> stone=<span class="dt">Writer</span>.where(<span class="st">:name=</span>>{<span class="st">:$regex=</span>><span class="st">"Stone"</span>}).first
> pp <span class="dt">Writer</span>.collection.find(<span class="st">:_id=</span>>stone.id).first
{<span class="st">:_id=</span>><span class="st">"nm0000231"</span>,
<span class="st">:name=</span>><span class="st">"Oliver Stone"</span>,
<span class="st">:movie_ids=</span>>[<span class="st">"tt0086250"</span>, <span class="st">"tt0091763"</span>]}</code></pre>
<p>If we add the writer to the movie, the writer receives an <code>updated_at</code> timestamp.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky26.writers << stone
> pp <span class="dt">Writer</span>.collection.find(<span class="st">:_id=</span>>stone.id).first
{<span class="st">:_id=</span>><span class="st">"nm0000231"</span>,
<span class="st">:name=</span>><span class="st">"Oliver Stone"</span>,
<span class="st">:movie_ids=</span>>[<span class="st">"tt0086250"</span>, <span class="st">"tt0091763"</span>, <span class="st">"tt9000001"</span>],
<span class="st">:updated_at=</span>><span class="dv">2015-11-28</span> <span class="dv">20</span>:<span class="dv">53</span>:<span class="dv">55</span> <span class="dt">UTC</span>}</code></pre>
<p>The odd thing found was that the source of the collection we navigated from does not get an <code>updated_at</code> change -- even when issuing save. This was found to be true no matter which end we started from.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky26.updated_at
=> <span class="dt">Sat</span>, <span class="dv">28</span> <span class="dt">Nov</span> <span class="dv">2015</span> <span class="dv">20</span>:<span class="dv">48</span>:<span class="dv">28</span> <span class="dt">UTC</span> +<span class="dv">00</span>:<span class="dv">00</span>
> pp <span class="dt">Movie</span>.collection.find(<span class="st">:_id=</span>>rocky26.id).first
{<span class="st">:_id=</span>><span class="st">"tt9000001"</span>,
<span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>,
<span class="st">:updated_at=</span>><span class="dv">2015-11-28</span> <span class="dv">20</span>:<span class="dv">48</span>:<span class="dv">28</span> <span class="dt">UTC</span>,
<span class="st">:created_at=</span>><span class="dv">2015-11-28</span> <span class="dv">20</span>:<span class="dv">47</span>:<span class="dv">59</span> <span class="dt">UTC</span>,
<span class="st">:year=</span>><span class="dv">2015</span>,
<span class="st">:writer_ids=</span>>[<span class="st">"nm0000231"</span>]}</code></pre>
<p>The object, can of course, be manually updated with a <code>touch</code> command.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky26.touch
> rocky26.updated_at
=> <span class="dt">Sat</span>, <span class="dv">28</span> <span class="dt">Nov</span> <span class="dv">2015</span> <span class="dv">21</span>:<span class="dv">00</span>:<span class="bn">05</span> <span class="dt">UTC</span> +<span class="dv">00</span>:<span class="dv">00</span> </code></pre>
<p>If we introduce a <code>touch</code> propagation property to the relationship we can get the <code>touch</code> command to cascade across the relationship. However, it appears that type of property is only available when the source of the <code>touch</code> has a single foreign key stored in its document. To demonstrate, we added the mixin to <code>Actor</code> and add the <code>touch</code> property to <code>MovieRole</code>.</p>
<pre><code>class Actor
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
...
end</code></pre>
<pre><code>class MovieRole
include Mongoid::Document
field :character, type: String
embedded_in :movie
...
belongs_to :actor, foreign_key: :_id, touch: true
...
end</code></pre>
<p>Our scenario starts off with an actor with no concept of when they were created or last updated. When we add a relationship to them from MovieRole (annotated with <code>touch: true</code>), the <code>updated_at</code> time of the actor is automatically updated.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">rocky26=<span class="dt">Movie</span>.create(<span class="st">:_id=</span>><span class="st">"tt9000001"</span>, <span class="st">:title=</span>><span class="st">"Rocky XXVI"</span>)
> damon=<span class="dt">Actor</span>.where(<span class="st">:name=</span>>{<span class="st">:$regex=</span>><span class="st">"Matt Da"</span>}).first
> damon.created_at
=> <span class="dv">nil</span>
> damon.updated_at
=> <span class="dv">nil</span>
> rocky=rocky26.roles.create(<span class="st">:actor=</span>>damon, <span class="st">:character=</span>><span class="st">"Rocky"</span>, <span class="st">:actorName=</span>><span class="st">"Matt"</span>, <span class="st">:main=</span>><span class="dv">true</span>)
> damon.updated_at
=> <span class="dt">Sat</span>, <span class="dv">28</span> <span class="dt">Nov</span> <span class="dv">2015</span> <span class="dv">21</span>:<span class="dv">18</span>:<span class="dv">38</span> <span class="dt">UTC</span> +<span class="dv">00</span>:<span class="dv">00</span> </code></pre>
<h3 id="constraints-and-validation">Constraints and Validation</h3>
<h3 id="field-validation">Field Validation</h3>
<p>ActiveModel validations can be added to Mongoid model classes. In the following example we declare that <code>name</code> must be present in the document.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Director</span>
include <span class="dt">Mongoid</span>::<span class="dt">Document</span>
field <span class="st">:name</span>, type: <span class="dt">String</span>
...
validates_presence_of <span class="st">:name</span>
<span class="kw">end</span></code></pre>
<p>To test our validation, we can attempt to create a new <code>Director</code> without a name.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> director=<span class="dt">Director</span>.create(<span class="st">:_id=</span>><span class="st">"12345"</span>)
=> <span class="co">#<Director _id: 12345, name: nil, residence_id: nil> </span></code></pre>
<p>Everything was quiet, but when we check for errors, we see that name cannot be blank.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> director.errors.count
=> <span class="dv">1</span>
> director.errors
=> <span class="co">#<ActiveModel::Errors:0x000000088ad830 @base=#<Director _id: 12345, name: nil, </span>
residence_id: <span class="dv">nil</span>>, <span class="ot">@messages</span>={<span class="st">:name=</span>>[<span class="st">"can't be blank"</span>]}> </code></pre>
<p>If we want an exception thrown instead, we add the bang ("!") character to the <code>create()</code> method to have Mongoid immediately throw an exception when encountering a validation error.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> director=<span class="dt">Director</span>.create!(<span class="st">:_id=</span>><span class="st">"12345"</span>)
<span class="dt">Mongoid</span>::<span class="dt">Errors</span>::<span class="dt">Validations</span>:
message:
<span class="dt">Validation</span> of <span class="dt">Director</span> failed.
summary:
<span class="dt">The</span> following errors were found: <span class="dt">Name</span> can<span class="st">'t be blank</span>
<span class="st">resolution:</span>
<span class="st"> Try persisting the document with valid data or remove the validations.</span></code></pre>
<h3 id="relationship-constraints">Relationship Constraints</h3>
<p>You can add dependency constraints to parents to inform Mongoid what to do with a child document when the parent the child is referencing is removed from the database. There are five(5) options when you include the default case. Cardinality of relationship does make a difference in some of the behavior.</p>
<ul>
<li>(default): Orphans the child document
<ul>
<li>1:1 and 1:M leaves the child with stale reference to the removed parent</li>
<li>M:M clears the child of the parent reference (acts like <code>:nullify</code>)</li>
</ul></li>
<li>nullify: Orphan the child document after setting the child foreign key to nil</li>
<li>destroy: Remove the child document after running model callbacks on the child</li>
<li>delete: Remove the child document without running model callbacks on the child
<ul>
<li>M:M does not remove the child document from database (acts like <code>:nullify</code>)</li>
</ul></li>
<li>restrict: Raise an error if a child references the parent being removed</li>
</ul>
<p>The Mongoid documentation states <code>:nullify</code> is the default, but we have found a key difference in how <code>default</code> and <code>:nullify</code> leave the child orphaned for the non-M:M case as well as some of the activity performed with the database. For 1:1 annd 1:M cardinality relationships, the <code>default</code> case leaves the orphaned child untouched, with a stale foreign key reference to the removed parent. <code>:nullify</code> clears the foreign key from the child. Both will result in a <code>nil</code> parent returned when accessed, but there are differences in the database.</p>
<p><code>:restrict</code> will throw an error in all cases if a child still exists with a foreign key reference to the parent being removed.</p>
<p><code>:destroy</code> and <code>:delete</code> are functionally the same for 1:1 and 1:M relationships -- in that they remove the children when the parent gets deleted and will run/not-run callbacks on the children at that time depending on the whether <code>:delete</code> or <code>:destroy</code> is selected. We have found the M:M cardinality case to be different in this area. M:M <code>:delete</code> acts like <code>:nullify</code> and does not remove the child. You must use <code>:destroy</code> if you wish the child of an M:M relationship to be removed.</p>
<h4 id="demonstration">Demonstration</h4>
<p>Lets demonstrate with the <code>Movie</code> <code>sequel/sequel_to</code> 1:1 relationship (mapped using a custom FK <code>sequel_of</code>) and the <code>Movie</code>/<code>Writer</code> M:M relationship.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Movie</span>
has_and_belongs_to_many <span class="st">:writers</span>
has_one <span class="st">:sequel</span>, foreign_key: <span class="st">:sequel_of</span>, class_name:<span class="st">"Movie"</span>
belongs_to <span class="st">:sequel_to</span>, foreign_key: <span class="st">:sequel_of</span>, class_name:<span class="st">"Movie"</span></code></pre>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">Writer</span>
has_and_belongs_to_many <span class="st">:movies</span></code></pre>
<p>Lets follow the same script in each case. We are re-finding the parent movie so that we can start the relationship from scratch at the point of the removal.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">reload!
rocky30=<span class="dt">Movie</span>.create(<span class="st">:title=</span>><span class="st">"Rocky 30"</span>)
rocky31=<span class="dt">Movie</span>.create(<span class="st">:title=</span>><span class="st">"Rocky 31"</span>, <span class="st">:sequel_to=</span>>rocky30)
writer=rocky30.writers.create(<span class="st">:name=</span>><span class="st">"A Writer"</span>)
rocky30.id
<span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky30.id).first.writer_ids
<span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky31.id).first.sequel_of
<span class="dt">Writer</span>.where(<span class="st">:id=</span>>writer.id).first.movie_ids
rocky30=<span class="dt">Movie</span>.find(rocky30.id)
rocky30.destroy
<span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky30.id).exists?
<span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky30.id).first.writer_ids <span class="kw">if</span> <span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky30.id).exists?
<span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky31.id).exists?
<span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky31.id).first.sequel_of <span class="kw">if</span> <span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky31.id).exists?
<span class="dt">Writer</span>.where(<span class="st">:id=</span>>writer.id).exists?
<span class="dt">Writer</span>.where(<span class="st">:id=</span>>writer.id).first.movie_ids <span class="kw">if</span> <span class="dt">Writer</span>.where(<span class="st">:id=</span>>writer.id).exists?</code></pre>
<p>To clean-up, we can follow-up with</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">p <span class="dt">Movie</span>.where(<span class="st">:title=</span>>{<span class="st">:$regex=</span>><span class="st">"Rocky 3[0-1]"</span>}).delete_all; \
<span class="dt">Writer</span>.where(<span class="st">:name=</span>>{<span class="st">:$regex=</span>><span class="st">"A Writer"</span>}).delete_all</code></pre>
<h4 id="callbacks">Callbacks</h4>
<p>To add some clarity to relationship handling and the <code>delete</code> versus <code>destroy</code> case, we add some callbacks to the <code>Movie</code> and <code>Writer</code> model classes to be notified when the document is being removed from the database.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"> before_destroy <span class="kw">do</span> |doc|
puts <span class="st">"before_destroy Movie callback for </span><span class="ot">#{</span>doc.id<span class="ot">}</span><span class="st">, "</span>\
<span class="st">"sequel_to=</span><span class="ot">#{</span>doc.sequel_to<span class="ot">}</span><span class="st">, writers=</span><span class="ot">#{</span>doc.writer_ids<span class="ot">}</span><span class="st">"</span>
<span class="kw">end</span>
after_destroy <span class="kw">do</span> |doc|
puts <span class="st">"after_destroy Movie callback for </span><span class="ot">#{</span>doc.id<span class="ot">}</span><span class="st">, "</span>\
<span class="st">"sequel_to=</span><span class="ot">#{</span>doc.sequel_to<span class="ot">}</span><span class="st">, writers=</span><span class="ot">#{</span>doc.writer_ids<span class="ot">}</span><span class="st">"</span>
<span class="kw">end</span></code></pre>
<pre class="sourceCode ruby"><code class="sourceCode ruby"> before_destroy <span class="kw">do</span> |doc|
puts <span class="st">"before_destroy Writer callback for </span><span class="ot">#{</span>doc.id<span class="ot">}</span><span class="st">, "</span>\
<span class="st">"movies=</span><span class="ot">#{</span>doc.movie_ids<span class="ot">}</span><span class="st">"</span>
<span class="kw">end</span>
after_destroy <span class="kw">do</span> |doc|
puts <span class="st">"after_destroy Writer callback for </span><span class="ot">#{</span>doc.id<span class="ot">}</span><span class="st">, "</span>\
<span class="st">"movies=</span><span class="ot">#{</span>doc.movie_ids<span class="ot">}</span><span class="st">"</span>
<span class="kw">end</span></code></pre>
<p>Mongoid document states callbacks should be reserved for cross-cutting (e.g., send messages) behavior and and not business behavior. The documentation also states that the amount of callbacks should be limited within an object tree for performance reasons.</p>
<p>Note the callbacks are called when <code>destroy</code> is called on the object.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> <span class="dt">Movie</span>.new.destroy
before_destroy <span class="dt">Movie</span> callback <span class="kw">for</span> 5680088fe301d06376000006, sequel_to=, writers=[]
D, | {<span class="st">"delete"</span>=><span class="st">"movies"</span>, <span class="st">"deletes"</span>=>[{<span class="st">"q"</span>=>{<span class="st">"_id"</span>=><span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'5680088fe301d06376000006'</span>)}...
after_destroy <span class="dt">Movie</span> callback <span class="kw">for</span> 5680088fe301d06376000006, sequel_to=, writers=[]
=> <span class="dv">true</span>
> <span class="dt">Writer</span>.new.destroy
before_destroy <span class="dt">Writer</span> callback <span class="kw">for</span> 56800908e301d06376000008, movies=[]
D, | {<span class="st">"delete"</span>=><span class="st">"writers"</span>, <span class="st">"deletes"</span>=>[{<span class="st">"q"</span>=>{<span class="st">"_id"</span>=><span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56800908e301d06376000008'</span>)}...
after_destroy <span class="dt">Writer</span> callback <span class="kw">for</span> 56800908e301d06376000008, movies=[]
=> <span class="dv">true</span> </code></pre>
<p>But not called when only <code>delete</code> is called.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> <span class="dt">Movie</span>.new.delete
D, | {<span class="st">"delete"</span>=><span class="st">"movies"</span>, <span class="st">"deletes"</span>=>[{<span class="st">"q"</span>=>{<span class="st">"_id"</span>=><span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56800896e301d06376000007'</span>)}...
=> <span class="dv">true</span>
> <span class="dt">Writer</span>.new.delete
D, | {<span class="st">"delete"</span>=><span class="st">"writers"</span>, <span class="st">"deletes"</span>=>[{<span class="st">"q"</span>=>{<span class="st">"_id"</span>=><span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'5680090ce301d06376000009'</span>)}...
=> <span class="dv">true</span> </code></pre>
<h4 id="relationship-constraints-dependent-destroy">Relationship Constraints: <code>dependent: :destroy</code></h4>
<p>To immediately demonstrate callbacks, lets look at the <code>:destroy</code> case.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"> has_and_belongs_to_many <span class="st">:writers</span>, dependent: <span class="st">:destroy</span>
has_one <span class="st">:sequel</span>, foreign_key: <span class="st">:sequel_of</span>, class_name:<span class="st">"Movie"</span>, dependent: <span class="st">:destroy</span></code></pre>
<p>We start in our standard state.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky30.id
=> <span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000016'</span>)
> <span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky30.id).first.writer_ids
=> [<span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000018'</span>)]
> <span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky31.id).first.sequel_of
=> <span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000016'</span>)
> <span class="dt">Writer</span>.where(<span class="st">:id=</span>>writer.id).first.movie_ids
=> [<span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000016'</span>)]
> rocky30=<span class="dt">Movie</span>.find(rocky30.id)
> rocky30.destroy</code></pre>
<p>The callbacks start with the parent object being called back.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">before_destroy <span class="dt">Movie</span> callback <span class="kw">for</span> 56801498e301d06376000016,
sequel_to=, writers=[<span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000018'</span>)]</code></pre>
<p><code>Writer</code>s are retrieved by primary key (because the M:M relation stores the PK on the parent-side). The writer(s) are retrieved so that <code>destroy</code> callbacks could be issued and provided the document state during the callback. Each writer is removed from the database and the writer is also removed from the parent movies having that writer (including the one being removed in this case).</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">D, | {<span class="st">"find"</span>=><span class="st">"writers"</span>, <span class="st">"filter"</span>=>
{<span class="st">"$and"</span>=>[{<span class="st">"_id"</span>=>{<span class="st">"$in"</span>=>[<span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000018'</span>)]}}]}}
before_destroy <span class="dt">Writer</span> callback <span class="kw">for</span> 56801498e301d06376000018,
movies=[<span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000016'</span>)]
D, | {<span class="st">"delete"</span>=><span class="st">"writers"</span>, <span class="st">"deletes"</span>=>[{<span class="st">"q"</span>=>{<span class="st">"_id"</span>=><span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000018'</span>)}, ...
D, | {<span class="st">"update"</span>=><span class="st">"movies"</span>, <span class="st">"updates"</span>=>[{
<span class="st">"q"</span>=>{<span class="st">"$and"</span>=>[{<span class="st">"_id"</span>=>{<span class="st">"$in"</span>=>[<span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000016'</span>)]}}]},
<span class="st">"u"</span>=>{<span class="st">"$pull"</span>=>{<span class="st">"writer_ids"</span>=><span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000018'</span>)}}...
after_destroy <span class="dt">Writer</span> callback <span class="kw">for</span> 56801498e301d06376000018,
movies=[<span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000016'</span>)]</code></pre>
<p>Sequel <code>Movie</code>s are located by foreign key (<code>sequel_of</code>), retrieved, and callbacks invoked. There is an extra call to the database in this case to locate the sequel of a sequel.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">D, | {<span class="st">"find"</span>=><span class="st">"movies"</span>, <span class="st">"filter"</span>=>{<span class="st">"sequel_of"</span>=><span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000016'</span>)}}
before_destroy <span class="dt">Movie</span> callback <span class="kw">for</span> 56801498e301d06376000017,
sequel_to=<span class="co">#<Movie:0x00000005349130>, writers=[]</span>
D, | {<span class="st">"find"</span>=><span class="st">"movies"</span>, <span class="st">"filter"</span>=>{<span class="st">"sequel_of"</span>=><span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000017'</span>)}}
D, | {<span class="st">"delete"</span>=><span class="st">"movies"</span>, <span class="st">"deletes"</span>=>[{<span class="st">"q"</span>=>{<span class="st">"_id"</span>=><span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000017'</span>)},...
after_destroy <span class="dt">Movie</span> callback <span class="kw">for</span> 56801498e301d06376000017,
sequel_to=<span class="co">#<Movie:0x00000005349130>, writers=[]</span></code></pre>
<p>At this point, the parent <code>Movie</code> is removed and any writer still having a reference to this movie has their foreign key removed. This seems unnecessary, but remember this is all done outside of a transaction -- so redundant calls may be useful.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">D, | {<span class="st">"delete"</span>=><span class="st">"movies"</span>, <span class="st">"deletes"</span>=>[{<span class="st">"q"</span>=>{<span class="st">"_id"</span>=><span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000016'</span>)},...
D, | {<span class="st">"update"</span>=><span class="st">"writers"</span>, <span class="st">"updates"</span>=>[{
<span class="st">"q"</span>=>{<span class="st">"$and"</span>=>[{<span class="st">"_id"</span>=>{<span class="st">"$in"</span>=>[<span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000018'</span>)]}}]},
<span class="st">"u"</span>=>{<span class="st">"$pull"</span>=>{<span class="st">"movie_ids"</span>=><span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000016'</span>)}},...
after_destroy <span class="dt">Movie</span> callback <span class="kw">for</span> 56801498e301d06376000016,
sequel_to=, writers=[<span class="dt">BSON</span>::<span class="dt">ObjectId</span>(<span class="st">'56801498e301d06376000018'</span>)]
=> <span class="dv">true</span> </code></pre>
<p>The parent and all children have been removed for the <code>dependent: :destroy</code> case.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> <span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky30.id).exists?
=> <span class="dv">false</span>
> <span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky30.id).first.writer_ids <span class="kw">if</span> <span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky30.id).exists?
=> <span class="dv">nil</span>
> <span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky31.id).exists?
=> <span class="dv">false</span>
> <span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky31.id).first.sequel_of <span class="kw">if</span> <span class="dt">Movie</span>.where(<span class="st">:id=</span>>rocky31.id).exists?
=> <span class="dv">nil</span>
> <span class="dt">Writer</span>.where(<span class="st">:id=</span>>writer.id).exists?
=> <span class="dv">false</span>
> <span class="dt">Writer</span>.where(<span class="st">:id=</span>>writer.id).first.movie_ids <span class="kw">if</span> <span class="dt">Writer</span>.where(<span class="st">:id=</span>>writer.id).exists?
=> <span class="dv">nil</span> </code></pre>
<h4 id="relationship-constraints-dependent-delete">Relationship Constraints: <code>dependent: :delete</code></h4>
<p>To further demonstrate callbacks, lets look at the <code>:delete</code> case. The two cases have primarily the same end functionality except that <code>:delete</code> does not invoke callbacks on the children. However, we do see a difference in how <code>:delete</code> and <code>:destroy</code> work for the M:M case.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"> has_and_belongs_to_many <span class="st">:writers</span>, dependent: <span class="st">:delete</span>
has_one <span class="st">:sequel</span>, foreign_key: <span class="st">:sequel_of</span>, class_name:<span class="st">"Movie"</span>, dependent: <span class="st">:delete</span></code></pre>
<p>We start in our standard state. The destroy callbacks are still invoked on the parent because we have called <code>destroy()</code> on the parent. The impact of our change should be restricted to what occurs for the child.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">> rocky30.id