-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassociation_basics.html
2242 lines (2001 loc) · 149 KB
/
association_basics.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Active Record Associations — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" data-turbolinks-track="reload">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="javascripts/syntaxhighlighter.js" data-turbolinks-track="reload"></script>
<script src="javascripts/turbolinks.js" data-turbolinks-track="reload"></script>
<script src="javascripts/guides.js" data-turbolinks-track="reload"></script>
<script src="javascripts/responsive-tables.js" data-turbolinks-track="reload"></script>
<meta property="og:title" content="Active Record Associations — Ruby on Rails Guides" />
<meta name="description" content="Active Record AssociationsThis guide covers the association features of Active Record.After reading this guide, you will know: How to declare associations between Active Record models. How to understand the various types of Active Record associations. How to use the methods added to your models by creating associations." />
<meta property="og:description" content="Active Record AssociationsThis guide covers the association features of Active Record.After reading this guide, you will know: How to declare associations between Active Record models. How to understand the various types of Active Record associations. How to use the methods added to your models by creating associations." />
<meta property="og:locale" content="en_US" />
<meta property="og:site_name" content="Ruby on Rails Guides" />
<meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" />
<meta property="og:type" content="website" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">공식 웹사이트 <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong>
<span class="red-button more-info-button">
루비온레일스 웹사이트
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="https://weblog.rubyonrails.org/">블로그</a></li>
<li class="more-info"><a href="https://guides.rubyonrails.org/">영문가이드</a></li>
<li class="more-info"><a href="https://api.rubyonrails.org/">레일스API</a></li>
<li class="more-info"><a href="https://stackoverflow.com/questions/tagged/ruby-on-rails">질문하기</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">GitHub에서 기여하기</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">홈</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">가이드 인덱스</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<div class="guides-section-container">
<div class="guides-section">
<dt>시작하면서</dt>
<dd><a href="getting_started.html">레일스로 시작하기</a></dd>
</div>
<div class="guides-section">
<dt>모델</dt>
<dd><a href="active_record_basics.html">액티브 레코드 기본</a></dd>
<dd><a href="active_record_migrations.html">액티브 레코드 마이그레이션</a></dd>
<dd><a href="active_record_validations.html">액티브 레코드 유효성 검증</a></dd>
<dd><a href="active_record_callbacks.html">액티브 레코드 콜백</a></dd>
<dd><a href="association_basics.html">Active Record Associations</a></dd>
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
</div>
<div class="guides-section">
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
</div>
<div class="guides-section">
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
</div>
<div class="guides-section">
<dt>Other Components</dt>
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
<dd><a href="active_job_basics.html">Active Job Basics</a></dd>
<dd><a href="active_storage_overview.html">Active Storage Overview</a></dd>
<dd><a href="action_cable_overview.html">Action Cable Overview</a></dd>
</div>
<div class="guides-section">
<dt>Digging Deeper</dt>
<dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd>
<dd><a href="testing.html">Testing Rails Applications</a></dd>
<dd><a href="security.html">Securing Rails Applications</a></dd>
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
<dd><a href="command_line.html">The Rails Command Line</a></dd>
<dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
<dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</a></dd>
<dd><a href="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</a></dd>
<dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd>
<dd><a href="api_app.html">Using Rails for API-only Applications</a></dd>
</div>
<div class="guides-section">
<dt>Extending Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd>
</div>
<div class="guides-section">
<dt>Contributions</dt>
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd>
</div>
<div class="guides-section">
<dt>Policies</dt>
<dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
</div>
<div class="guides-section">
<dt>Release Notes</dt>
<dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
<dd><a href="6_0_release_notes.html">Version 6.0 - August 2019</a></dd>
<dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd>
<dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd>
<dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd>
<dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd>
<dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd>
<dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd>
<dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd>
<dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd>
<dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd>
<dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd>
<dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd>
</div>
</div>
</div>
</li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">기여하기</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">가이드 인덱스</option>
<optgroup label="시작하면서">
<option value="getting_started.html">레일스로 시작하기</option>
</optgroup>
<optgroup label="모델">
<option value="active_record_basics.html">액티브 레코드 기본</option>
<option value="active_record_migrations.html">액티브 레코드 마이그레이션</option>
<option value="active_record_validations.html">액티브 레코드 유효성 검증</option>
<option value="active_record_callbacks.html">액티브 레코드 콜백</option>
<option value="association_basics.html">Active Record Associations</option>
<option value="active_record_querying.html">Active Record Query Interface</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
<option value="form_helpers.html">Action View Form Helpers</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller Overview</option>
<option value="routing.html">Rails Routing from the Outside In</option>
</optgroup>
<optgroup label="Other Components">
<option value="active_support_core_extensions.html">Active Support Core Extensions</option>
<option value="action_mailer_basics.html">Action Mailer Basics</option>
<option value="active_job_basics.html">Active Job Basics</option>
<option value="active_storage_overview.html">Active Storage Overview</option>
<option value="action_cable_overview.html">Action Cable Overview</option>
</optgroup>
<optgroup label="Digging Deeper">
<option value="i18n.html">Rails Internationalization (I18n) API</option>
<option value="testing.html">Testing Rails Applications</option>
<option value="security.html">Securing Rails Applications</option>
<option value="debugging_rails_applications.html">Debugging Rails Applications</option>
<option value="configuring.html">Configuring Rails Applications</option>
<option value="command_line.html">The Rails Command Line</option>
<option value="asset_pipeline.html">The Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
<option value="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</option>
<option value="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</option>
<option value="caching_with_rails.html">Caching with Rails: An Overview</option>
<option value="api_app.html">Using Rails for API-only Applications</option>
</optgroup>
<optgroup label="Extending Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">Creating and Customizing Rails Generators & Templates</option>
</optgroup>
<optgroup label="Contributions">
<option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
<option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option>
</optgroup>
<optgroup label="Policies">
<option value="maintenance_policy.html">Maintenance Policy</option>
</optgroup>
<optgroup label="Release Notes">
<option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
<option value="6_0_release_notes.html">Version 6.0 - August 2019</option>
<option value="5_2_release_notes.html">Version 5.2 - April 2018</option>
<option value="5_1_release_notes.html">Version 5.1 - April 2017</option>
<option value="5_0_release_notes.html">Version 5.0 - June 2016</option>
<option value="4_2_release_notes.html">Version 4.2 - December 2014</option>
<option value="4_1_release_notes.html">Version 4.1 - April 2014</option>
<option value="4_0_release_notes.html">Version 4.0 - June 2013</option>
<option value="3_2_release_notes.html">Version 3.2 - January 2012</option>
<option value="3_1_release_notes.html">Version 3.1 - August 2011</option>
<option value="3_0_release_notes.html">Version 3.0 - August 2010</option>
<option value="2_3_release_notes.html">Version 2.3 - March 2009</option>
<option value="2_2_release_notes.html">Version 2.2 - November 2008</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Active Record Associations</h2><p>This guide covers the association features of Active Record.</p><p>After reading this guide, you will know:</p>
<ul>
<li>How to declare associations between Active Record models.</li>
<li>How to understand the various types of Active Record associations.</li>
<li>How to use the methods added to your models by creating associations.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#why-associations-questionmark">Why Associations?</a></li>
<li>
<a href="#the-types-of-associations">The Types of Associations</a>
<ul>
<li><a href="#the-belongs-to-association">The <code>belongs_to</code> Association</a></li>
<li><a href="#the-has-one-association">The <code>has_one</code> Association</a></li>
<li><a href="#the-has-many-association">The <code>has_many</code> Association</a></li>
<li><a href="#the-has-many-through-association">The <code>has_many :through</code> Association</a></li>
<li><a href="#the-has-one-through-association">The <code>has_one :through</code> Association</a></li>
<li><a href="#the-has-and-belongs-to-many-association">The <code>has_and_belongs_to_many</code> Association</a></li>
<li><a href="#choosing-between-belongs-to-and-has-one">Choosing Between <code>belongs_to</code> and <code>has_one</code></a></li>
<li><a href="#choosing-between-has-many-through-and-has-and-belongs-to-many">Choosing Between <code>has_many :through</code> and <code>has_and_belongs_to_many</code></a></li>
<li><a href="#polymorphic-associations">Polymorphic Associations</a></li>
<li><a href="#self-joins">Self Joins</a></li>
</ul>
</li>
<li>
<a href="#tips-tricks-and-warnings">Tips, Tricks, and Warnings</a>
<ul>
<li><a href="#controlling-caching">Controlling Caching</a></li>
<li><a href="#avoiding-name-collisions">Avoiding Name Collisions</a></li>
<li><a href="#updating-the-schema">Updating the Schema</a></li>
<li><a href="#controlling-association-scope">Controlling Association Scope</a></li>
<li><a href="#bi-directional-associations">Bi-directional Associations</a></li>
</ul>
</li>
<li>
<a href="#detailed-association-reference">Detailed Association Reference</a>
<ul>
<li><a href="#belongs-to-association-reference"><code>belongs_to</code> Association Reference</a></li>
<li><a href="#has-one-association-reference"><code>has_one</code> Association Reference</a></li>
<li><a href="#has-many-association-reference"><code>has_many</code> Association Reference</a></li>
<li><a href="#has-and-belongs-to-many-association-reference"><code>has_and_belongs_to_many</code> Association Reference</a></li>
<li><a href="#association-callbacks">Association Callbacks</a></li>
<li><a href="#association-extensions">Association Extensions</a></li>
</ul>
</li>
<li><a href="#single-table-inheritance">Single Table Inheritance</a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="why-associations-questionmark"><a class="anchorlink" href="#why-associations-questionmark">1 Why Associations?</a></h3><p>In Rails, an <em>association</em> is a connection between two Active Record models. Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for authors and a model for books. Each author can have many books. Without associations, the model declarations would look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Author < ApplicationRecord
end
class Book < ApplicationRecord
end
</pre>
</div>
<p>Now, suppose we wanted to add a new book for an existing author. We'd need to do something like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@book = Book.create(published_at: Time.now, author_id: @author.id)
</pre>
</div>
<p>Or consider deleting an author, and ensuring that all of its books get deleted as well:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@books = Book.where(author_id: @author.id)
@books.each do |book|
book.destroy
end
@author.destroy
</pre>
</div>
<p>With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up authors and books:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Author < ApplicationRecord
has_many :books, dependent: :destroy
end
class Book < ApplicationRecord
belongs_to :author
end
</pre>
</div>
<p>With this change, creating a new book for a particular author is easier:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@book = @author.books.create(published_at: Time.now)
</pre>
</div>
<p>Deleting an author and all of its books is <em>much</em> easier:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@author.destroy
</pre>
</div>
<p>To learn more about the different types of associations, read the next section of this guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.</p><h3 id="the-types-of-associations"><a class="anchorlink" href="#the-types-of-associations">2 The Types of Associations</a></h3><p>Rails supports six types of associations:</p>
<ul>
<li><code>belongs_to</code></li>
<li><code>has_one</code></li>
<li><code>has_many</code></li>
<li><code>has_many :through</code></li>
<li><code>has_one :through</code></li>
<li><code>has_and_belongs_to_many</code></li>
</ul>
<p>Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model <code>belongs_to</code> another, you instruct Rails to maintain <a href="https://en.wikipedia.org/wiki/Unique_key">Primary Key</a>-<a href="https://en.wikipedia.org/wiki/Foreign_key">Foreign Key</a> information between instances of the two models, and you also get a number of utility methods added to your model.</p><p>In the remainder of this guide, you'll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.</p><h4 id="the-belongs-to-association"><a class="anchorlink" href="#the-belongs-to-association">2.1 The <code>belongs_to</code> Association</a></h4><p>A <code>belongs_to</code> association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes authors and books, and each book can be assigned to exactly one author, you'd declare the book model this way:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Book < ApplicationRecord
belongs_to :author
end
</pre>
</div>
<p><img src="images/association_basics/belongs_to.png" alt="belongs_to Association Diagram"></p><div class="note"><p><code>belongs_to</code> associations <em>must</em> use the singular term. If you used the pluralized form in the above example for the <code>author</code> association in the <code>Book</code> model and tried to create the instance by <code>Book.create(authors: @author)</code>, you would be told that there was an "uninitialized constant Book::Authors". This is because Rails automatically infers the class name from the association name. If the association name is wrongly pluralized, then the inferred class will be wrongly pluralized too.</p></div><p>The corresponding migration might look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreateBooks < ActiveRecord::Migration[5.0]
def change
create_table :authors do |t|
t.string :name
t.timestamps
end
create_table :books do |t|
t.belongs_to :author
t.datetime :published_at
t.timestamps
end
end
end
</pre>
</div>
<h4 id="the-has-one-association"><a class="anchorlink" href="#the-has-one-association">2.2 The <code>has_one</code> Association</a></h4><p>A <code>has_one</code> association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Supplier < ApplicationRecord
has_one :account
end
</pre>
</div>
<p><img src="images/association_basics/has_one.png" alt="has_one Association Diagram"></p><p>The corresponding migration might look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreateSuppliers < ActiveRecord::Migration[5.0]
def change
create_table :suppliers do |t|
t.string :name
t.timestamps
end
create_table :accounts do |t|
t.belongs_to :supplier
t.string :account_number
t.timestamps
end
end
end
</pre>
</div>
<p>Depending on the use case, you might also need to create a unique index and/or
a foreign key constraint on the supplier column for the accounts table. In this
case, the column definition might look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
create_table :accounts do |t|
t.belongs_to :supplier, index: { unique: true }, foreign_key: true
# ...
end
</pre>
</div>
<h4 id="the-has-many-association"><a class="anchorlink" href="#the-has-many-association">2.3 The <code>has_many</code> Association</a></h4><p>A <code>has_many</code> association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a <code>belongs_to</code> association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing authors and books, the author model could be declared like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Author < ApplicationRecord
has_many :books
end
</pre>
</div>
<div class="note"><p>The name of the other model is pluralized when declaring a <code>has_many</code> association.</p></div><p><img src="images/association_basics/has_many.png" alt="has_many Association Diagram"></p><p>The corresponding migration might look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreateAuthors < ActiveRecord::Migration[5.0]
def change
create_table :authors do |t|
t.string :name
t.timestamps
end
create_table :books do |t|
t.belongs_to :author
t.datetime :published_at
t.timestamps
end
end
end
</pre>
</div>
<h4 id="the-has-many-through-association"><a class="anchorlink" href="#the-has-many-through-association">2.4 The <code>has_many :through</code> Association</a></h4><p>A <code>has_many :through</code> association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding <em>through</em> a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Physician < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ApplicationRecord
belongs_to :physician
belongs_to :patient
end
class Patient < ApplicationRecord
has_many :appointments
has_many :physicians, through: :appointments
end
</pre>
</div>
<p><img src="images/association_basics/has_many_through.png" alt="has_many :through Association Diagram"></p><p>The corresponding migration might look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreateAppointments < ActiveRecord::Migration[5.0]
def change
create_table :physicians do |t|
t.string :name
t.timestamps
end
create_table :patients do |t|
t.string :name
t.timestamps
end
create_table :appointments do |t|
t.belongs_to :physician
t.belongs_to :patient
t.datetime :appointment_date
t.timestamps
end
end
end
</pre>
</div>
<p>The collection of join models can be managed via the <a href="#has-many-association-reference"><code>has_many</code> association methods</a>.
For example, if you assign:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
physician.patients = patients
</pre>
</div>
<p>Then new join models are automatically created for the newly associated objects.
If some that existed previously are now missing, then their join rows are automatically deleted.</p><div class="warning"><p>Automatic deletion of join models is direct, no destroy callbacks are triggered.</p></div><p>The <code>has_many :through</code> association is also useful for setting up "shortcuts" through nested <code>has_many</code> associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Document < ApplicationRecord
has_many :sections
has_many :paragraphs, through: :sections
end
class Section < ApplicationRecord
belongs_to :document
has_many :paragraphs
end
class Paragraph < ApplicationRecord
belongs_to :section
end
</pre>
</div>
<p>With <code>through: :sections</code> specified, Rails will now understand:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@document.paragraphs
</pre>
</div>
<h4 id="the-has-one-through-association"><a class="anchorlink" href="#the-has-one-through-association">2.5 The <code>has_one :through</code> Association</a></h4><p>A <code>has_one :through</code> association sets up a one-to-one connection with another model. This association indicates
that the declaring model can be matched with one instance of another model by proceeding <em>through</em> a third model.
For example, if each supplier has one account, and each account is associated with one account history, then the
supplier model could look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Supplier < ApplicationRecord
has_one :account
has_one :account_history, through: :account
end
class Account < ApplicationRecord
belongs_to :supplier
has_one :account_history
end
class AccountHistory < ApplicationRecord
belongs_to :account
end
</pre>
</div>
<p><img src="images/association_basics/has_one_through.png" alt="has_one :through Association Diagram"></p><p>The corresponding migration might look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreateAccountHistories < ActiveRecord::Migration[5.0]
def change
create_table :suppliers do |t|
t.string :name
t.timestamps
end
create_table :accounts do |t|
t.belongs_to :supplier
t.string :account_number
t.timestamps
end
create_table :account_histories do |t|
t.belongs_to :account
t.integer :credit_rating
t.timestamps
end
end
end
</pre>
</div>
<h4 id="the-has-and-belongs-to-many-association"><a class="anchorlink" href="#the-has-and-belongs-to-many-association">2.6 The <code>has_and_belongs_to_many</code> Association</a></h4><p>A <code>has_and_belongs_to_many</code> association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Assembly < ApplicationRecord
has_and_belongs_to_many :parts
end
class Part < ApplicationRecord
has_and_belongs_to_many :assemblies
end
</pre>
</div>
<p><img src="images/association_basics/habtm.png" alt="has_and_belongs_to_many Association Diagram"></p><p>The corresponding migration might look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreateAssembliesAndParts < ActiveRecord::Migration[5.0]
def change
create_table :assemblies do |t|
t.string :name
t.timestamps
end
create_table :parts do |t|
t.string :part_number
t.timestamps
end
create_table :assemblies_parts, id: false do |t|
t.belongs_to :assembly
t.belongs_to :part
end
end
end
</pre>
</div>
<h4 id="choosing-between-belongs-to-and-has-one"><a class="anchorlink" href="#choosing-between-belongs-to-and-has-one">2.7 Choosing Between <code>belongs_to</code> and <code>has_one</code></a></h4><p>If you want to set up a one-to-one relationship between two models, you'll need to add <code>belongs_to</code> to one, and <code>has_one</code> to the other. How do you know which is which?</p><p>The distinction is in where you place the foreign key (it goes on the table for the class declaring the <code>belongs_to</code> association), but you should give some thought to the actual meaning of the data as well. The <code>has_one</code> relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Supplier < ApplicationRecord
has_one :account
end
class Account < ApplicationRecord
belongs_to :supplier
end
</pre>
</div>
<p>The corresponding migration might look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreateSuppliers < ActiveRecord::Migration[5.2]
def change
create_table :suppliers do |t|
t.string :name
t.timestamps
end
create_table :accounts do |t|
t.bigint :supplier_id
t.string :account_number
t.timestamps
end
add_index :accounts, :supplier_id
end
end
</pre>
</div>
<div class="note"><p>Using <code>t.bigint :supplier_id</code> makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using <code>t.references :supplier</code> instead.</p></div><h4 id="choosing-between-has-many-through-and-has-and-belongs-to-many"><a class="anchorlink" href="#choosing-between-has-many-through-and-has-and-belongs-to-many">2.8 Choosing Between <code>has_many :through</code> and <code>has_and_belongs_to_many</code></a></h4><p>Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use <code>has_and_belongs_to_many</code>, which allows you to make the association directly:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Assembly < ApplicationRecord
has_and_belongs_to_many :parts
end
class Part < ApplicationRecord
has_and_belongs_to_many :assemblies
end
</pre>
</div>
<p>The second way to declare a many-to-many relationship is to use <code>has_many :through</code>. This makes the association indirectly, through a join model:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Assembly < ApplicationRecord
has_many :manifests
has_many :parts, through: :manifests
end
class Manifest < ApplicationRecord
belongs_to :assembly
belongs_to :part
end
class Part < ApplicationRecord
has_many :manifests
has_many :assemblies, through: :manifests
end
</pre>
</div>
<p>The simplest rule of thumb is that you should set up a <code>has_many :through</code> relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a <code>has_and_belongs_to_many</code> relationship (though you'll need to remember to create the joining table in the database).</p><p>You should use <code>has_many :through</code> if you need validations, callbacks, or extra attributes on the join model.</p><h4 id="polymorphic-associations"><a class="anchorlink" href="#polymorphic-associations">2.9 Polymorphic Associations</a></h4><p>A slightly more advanced twist on associations is the <em>polymorphic association</em>. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
end
class Employee < ApplicationRecord
has_many :pictures, as: :imageable
end
class Product < ApplicationRecord
has_many :pictures, as: :imageable
end
</pre>
</div>
<p>You can think of a polymorphic <code>belongs_to</code> declaration as setting up an interface that any other model can use. From an instance of the <code>Employee</code> model, you can retrieve a collection of pictures: <code>@employee.pictures</code>.</p><p>Similarly, you can retrieve <code>@product.pictures</code>.</p><p>If you have an instance of the <code>Picture</code> model, you can get to its parent via <code>@picture.imageable</code>. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreatePictures < ActiveRecord::Migration[5.2]
def change
create_table :pictures do |t|
t.string :name
t.bigint :imageable_id
t.string :imageable_type
t.timestamps
end
add_index :pictures, [:imageable_type, :imageable_id]
end
end
</pre>
</div>
<p>This migration can be simplified by using the <code>t.references</code> form:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.string :name
t.references :imageable, polymorphic: true
t.timestamps
end
end
end
</pre>
</div>
<p><img src="images/association_basics/polymorphic.png" alt="Polymorphic Association Diagram"></p><h4 id="self-joins"><a class="anchorlink" href="#self-joins">2.10 Self Joins</a></h4><p>In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Employee < ApplicationRecord
has_many :subordinates, class_name: "Employee",
foreign_key: "manager_id"
belongs_to :manager, class_name: "Employee", optional: true
end
</pre>
</div>
<p>With this setup, you can retrieve <code>@employee.subordinates</code> and <code>@employee.manager</code>.</p><p>In your migrations/schema, you will add a references column to the model itself.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreateEmployees < ActiveRecord::Migration[5.0]
def change
create_table :employees do |t|
t.references :manager
t.timestamps
end
end
end
</pre>
</div>
<h3 id="tips-tricks-and-warnings"><a class="anchorlink" href="#tips-tricks-and-warnings">3 Tips, Tricks, and Warnings</a></h3><p>Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:</p>
<ul>
<li>Controlling caching</li>
<li>Avoiding name collisions</li>
<li>Updating the schema</li>
<li>Controlling association scope</li>
<li>Bi-directional associations</li>
</ul>
<h4 id="controlling-caching"><a class="anchorlink" href="#controlling-caching">3.1 Controlling Caching</a></h4><p>All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
author.books # retrieves books from the database
author.books.size # uses the cached copy of books
author.books.empty? # uses the cached copy of books
</pre>
</div>
<p>But what if you want to reload the cache, because data might have been changed by some other part of the application? Just call <code>reload</code> on the association:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
author.books # retrieves books from the database
author.books.size # uses the cached copy of books
author.books.reload.empty? # discards the cached copy of books
# and goes back to the database
</pre>
</div>
<h4 id="avoiding-name-collisions"><a class="anchorlink" href="#avoiding-name-collisions">3.2 Avoiding Name Collisions</a></h4><p>You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of <code>ActiveRecord::Base</code>. The association method would override the base method and break things. For instance, <code>attributes</code> or <code>connection</code> are bad names for associations.</p><h4 id="updating-the-schema"><a class="anchorlink" href="#updating-the-schema">3.3 Updating the Schema</a></h4><p>Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For <code>belongs_to</code> associations you need to create foreign keys, and for <code>has_and_belongs_to_many</code> associations you need to create the appropriate join table.</p><h5 id="creating-foreign-keys-for-belongs-to-associations"><a class="anchorlink" href="#creating-foreign-keys-for-belongs-to-associations">3.3.1 Creating Foreign Keys for <code>belongs_to</code> Associations</a></h5><p>When you declare a <code>belongs_to</code> association, you need to create foreign keys as appropriate. For example, consider this model:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Book < ApplicationRecord
belongs_to :author
end
</pre>
</div>
<p>This declaration needs to be backed up by a corresponding foreign key column in the books table. For a brand new table, the migration might look something like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreateBooks < ActiveRecord::Migration[5.0]
def change
create_table :books do |t|
t.datetime :published_at
t.string :book_number
t.references :author
end
end
end
</pre>
</div>
<p>Whereas for an existing table, it might look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class AddAuthorToBooks < ActiveRecord::Migration[5.0]
def change
add_reference :books, :author
end
end
</pre>
</div>
<div class="note"><p>If you wish to <a href="/active_record_migrations.html#foreign-keys">enforce referential integrity at the database level</a>, add the <code>foreign_key: true</code> option to the ‘reference’ column declarations above.</p></div><h5 id="creating-join-tables-for-has-and-belongs-to-many-associations"><a class="anchorlink" href="#creating-join-tables-for-has-and-belongs-to-many-associations">3.3.2 Creating Join Tables for <code>has_and_belongs_to_many</code> Associations</a></h5><p>If you create a <code>has_and_belongs_to_many</code> association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the <code>:join_table</code> option, Active Record creates the name by using the lexical order of the class names. So a join between author and book models will give the default join table name of "authors_books" because "a" outranks "b" in lexical ordering.</p><div class="warning"><p>The precedence between model names is calculated using the <code><=></code> operator for <code>String</code>. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers" (because the underscore '_' is lexicographically <em>less</em> than 's' in common encodings).</p></div><p>Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Assembly < ApplicationRecord
has_and_belongs_to_many :parts
end
class Part < ApplicationRecord
has_and_belongs_to_many :assemblies
end
</pre>
</div>
<p>These need to be backed up by a migration to create the <code>assemblies_parts</code> table. This table should be created without a primary key:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreateAssembliesPartsJoinTable < ActiveRecord::Migration[5.2]
def change
create_table :assemblies_parts, id: false do |t|
t.bigint :assembly_id
t.bigint :part_id
end
add_index :assemblies_parts, :assembly_id
add_index :assemblies_parts, :part_id
end
end
</pre>
</div>
<p>We pass <code>id: false</code> to <code>create_table</code> because that table does not represent a model. That's required for the association to work properly. If you observe any strange behavior in a <code>has_and_belongs_to_many</code> association like mangled model IDs, or exceptions about conflicting IDs, chances are you forgot that bit.</p><p>You can also use the method <code>create_join_table</code></p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreateAssembliesPartsJoinTable < ActiveRecord::Migration[5.0]
def change
create_join_table :assemblies, :parts do |t|
t.index :assembly_id
t.index :part_id
end
end
end
</pre>
</div>
<h4 id="controlling-association-scope"><a class="anchorlink" href="#controlling-association-scope">3.4 Controlling Association Scope</a></h4><p>By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module MyApplication
module Business
class Supplier < ApplicationRecord
has_one :account
end
class Account < ApplicationRecord
belongs_to :supplier
end
end
end
</pre>
</div>
<p>This will work fine, because both the <code>Supplier</code> and the <code>Account</code> class are defined within the same scope. But the following will <em>not</em> work, because <code>Supplier</code> and <code>Account</code> are defined in different scopes:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module MyApplication
module Business
class Supplier < ApplicationRecord
has_one :account
end
end
module Billing
class Account < ApplicationRecord
belongs_to :supplier
end
end
end
</pre>
</div>
<p>To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module MyApplication
module Business
class Supplier < ApplicationRecord
has_one :account,
class_name: "MyApplication::Billing::Account"
end
end
module Billing
class Account < ApplicationRecord
belongs_to :supplier,
class_name: "MyApplication::Business::Supplier"
end
end
end
</pre>
</div>
<h4 id="bi-directional-associations"><a class="anchorlink" href="#bi-directional-associations">3.5 Bi-directional Associations</a></h4><p>It's normal for associations to work in two directions, requiring declaration on two different models:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Author < ApplicationRecord
has_many :books
end
class Book < ApplicationRecord
belongs_to :author
end
</pre>
</div>
<p>Active Record will attempt to automatically identify that these two models share a bi-directional association based on the association name. In this way, Active Record will only load one copy of the <code>Author</code> object, making your application more efficient and preventing inconsistent data:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
a = Author.first
b = a.books.first
a.first_name == b.author.first_name # => true
a.first_name = 'David'
a.first_name == b.author.first_name # => true
</pre>
</div>
<p>Active Record supports automatic identification for most associations with standard names. However, Active Record will not automatically identify bi-directional associations that contain a scope or any of the following options:</p>
<ul>
<li><code>:through</code></li>
<li><code>:foreign_key</code></li>
</ul>
<p>For example, consider the following model declarations:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Author < ApplicationRecord
has_many :books
end
class Book < ApplicationRecord
belongs_to :writer, class_name: 'Author', foreign_key: 'author_id'
end
</pre>
</div>
<p>Active Record will no longer automatically recognize the bi-directional association:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
a = Author.first
b = a.books.first
a.first_name == b.writer.first_name # => true
a.first_name = 'David'
a.first_name == b.writer.first_name # => false
</pre>
</div>
<p>Active Record provides the <code>:inverse_of</code> option so you can explicitly declare bi-directional associations:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Author < ApplicationRecord
has_many :books, inverse_of: 'writer'
end
class Book < ApplicationRecord
belongs_to :writer, class_name: 'Author', foreign_key: 'author_id'
end
</pre>
</div>
<p>By including the <code>:inverse_of</code> option in the <code>has_many</code> association declaration, Active Record will now recognize the bi-directional association:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
a = Author.first
b = a.books.first
a.first_name == b.writer.first_name # => true
a.first_name = 'David'
a.first_name == b.writer.first_name # => true
</pre>
</div>
<h3 id="detailed-association-reference"><a class="anchorlink" href="#detailed-association-reference">4 Detailed Association Reference</a></h3><p>The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.</p><h4 id="belongs-to-association-reference"><a class="anchorlink" href="#belongs-to-association-reference">4.1 <code>belongs_to</code> Association Reference</a></h4><p>The <code>belongs_to</code> association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use <code>has_one</code> instead.</p><h5 id="methods-added-by-belongs-to"><a class="anchorlink" href="#methods-added-by-belongs-to">4.1.1 Methods Added by <code>belongs_to</code></a></h5><p>When you declare a <code>belongs_to</code> association, the declaring class automatically gains 6 methods related to the association:</p>
<ul>
<li><code>association</code></li>
<li><code>association=(associate)</code></li>
<li><code>build_association(attributes = {})</code></li>
<li><code>create_association(attributes = {})</code></li>
<li><code>create_association!(attributes = {})</code></li>
<li><code>reload_association</code></li>
</ul>
<p>In all of these methods, <code>association</code> is replaced with the symbol passed as the first argument to <code>belongs_to</code>. For example, given the declaration:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Book < ApplicationRecord
belongs_to :author
end
</pre>
</div>
<p>Each instance of the <code>Book</code> model will have these methods:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
author
author=
build_author
create_author
create_author!
reload_author
</pre>
</div>
<div class="note"><p>When initializing a new <code>has_one</code> or <code>belongs_to</code> association you must use the <code>build_</code> prefix to build the association, rather than the <code>association.build</code> method that would be used for <code>has_many</code> or <code>has_and_belongs_to_many</code> associations. To create one, use the <code>create_</code> prefix.</p></div><h6 id="methods-added-by-belongs-to-association"><a class="anchorlink" href="#methods-added-by-belongs-to-association">4.1.1.1 <code>association</code></a></h6><p>The <code>association</code> method returns the associated object, if any. If no associated object is found, it returns <code>nil</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@author = @book.author
</pre>
</div>
<p>If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), call <code>#reload_association</code> on the parent object.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@author = @book.reload_author
</pre>
</div>
<h6 id="methods-added-by-belongs-to-association-associate"><a class="anchorlink" href="#methods-added-by-belongs-to-association-associate">4.1.1.2 <code>association=(associate)</code></a></h6><p>The <code>association=</code> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associated object and setting this object's foreign key to the same value.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@book.author = @author
</pre>
</div>
<h6 id="methods-added-by-belongs-to-build-association-attributes"><a class="anchorlink" href="#methods-added-by-belongs-to-build-association-attributes">4.1.1.3 <code>build_association(attributes = {})</code></a></h6><p>The <code>build_association</code> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will <em>not</em> yet be saved.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@author = @book.build_author(author_number: 123,
author_name: "John Doe")
</pre>
</div>
<h6 id="methods-added-by-belongs-to-create-association-attributes"><a class="anchorlink" href="#methods-added-by-belongs-to-create-association-attributes">4.1.1.4 <code>create_association(attributes = {})</code></a></h6><p>The <code>create_association</code> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through this object's foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object <em>will</em> be saved.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@author = @book.create_author(author_number: 123,
author_name: "John Doe")
</pre>
</div>
<h6 id="methods-added-by-belongs-to-create-association-bang-attributes"><a class="anchorlink" href="#methods-added-by-belongs-to-create-association-bang-attributes">4.1.1.5 <code>create_association!(attributes = {})</code></a></h6><p>Does the same as <code>create_association</code> above, but raises <code>ActiveRecord::RecordInvalid</code> if the record is invalid.</p><h5 id="options-for-belongs-to"><a class="anchorlink" href="#options-for-belongs-to">4.1.2 Options for <code>belongs_to</code></a></h5><p>While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the <code>belongs_to</code> association reference. Such customizations can easily be accomplished by passing options and scope blocks when you create the association. For example, this association uses two such options:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">