File: association_basics.md

package info (click to toggle)
rails 2%3A7.2.2.1%2Bdfsg-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 43,352 kB
  • sloc: ruby: 349,799; javascript: 30,703; yacc: 46; sql: 43; sh: 29; makefile: 27
file content (3304 lines) | stat: -rw-r--r-- 106,664 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**

Active Record Associations
==========================

This guide covers the association features of Active Record.

After reading this guide, you will know how to:

* Understand the various types of associations.
* Declare associations between Active Record models.
* Choose the right association type for your models.
* Use Single Table Inheritance.
* Setting up and using Delegated Types.

--------------------------------------------------------------------------------

Associations Overview
-----------------

Active Record associations allow you to define relationships between models.
_Associations_ are implemented as special macro style calls that make it easy to
tell Rails how your models relate to each other, which helps you manage your
data more effectively, and makes common operations simpler and easier to read.

INFO: A macro-style call is a method that generates or modifies other methods at
runtime, allowing for concise and expressive declarations of functionality, such
as defining model associations in Rails. For example, `has_many :comments`.

When you set up an association, Rails helps define and manage the [Primary
Key](https://en.wikipedia.org/wiki/Primary_key) and [Foreign
Key](https://en.wikipedia.org/wiki/Foreign_key) relationships between instances
of the two models, while the database ensures that your data stays consistent
and properly linked.

This makes it easy to keep track of which records are related. It also adds
useful methods to your models so you can work with related data more easily.

Consider a simple Rails application with models for authors and books.

### Without Associations

Without associations, creating and deleting books for that author would require
a tedious and manual process. Here's what that would look like:

```ruby
class CreateAuthors < ActiveRecord::Migration[7.2]
  def change
    create_table :authors do |t|
      t.string :name
      t.timestamps
    end

    create_table :books do |t|
      t.references :author
      t.datetime :published_at
      t.timestamps
    end
  end
end
```

```ruby
class Author < ApplicationRecord
end

class Book < ApplicationRecord
end
```

To add a new book for an existing author, you'd need to provide the `author_id`
value when creating the book.

```ruby
@book = Book.create(author_id: @author.id, published_at: Time.now)
```

To delete an author and ensure all their books are also deleted, you need to
retrieve all the author's `books`, loop through each `book` to destroy it, and
then destroy the author.

```ruby
@books = Book.where(author_id: @author.id)
@books.each do |book|
  book.destroy
end
@author.destroy
```

### Using Associations

However, with associations, we can streamline these operations, as well as
others, by explicitly informing Rails about the relationship between the two
models. Here's the revised code for setting up authors and books using
associations:

```ruby
class Author < ApplicationRecord
  has_many :books, dependent: :destroy
end

class Book < ApplicationRecord
  belongs_to :author
end
```

With this change, creating a new book for a particular author is simpler:

```ruby
@book = @author.books.create(published_at: Time.now)
```

Deleting an author and all of its books is much easier:

```ruby
@author.destroy
```

When you set up an association in Rails, you still need to create a
[migration](active_record_migrations.html) to ensure that the database is
properly configured to handle the association. This migration will need to add
the necessary foreign key columns to your database tables.

For example, if you set up a `belongs_to :author` association in the `Book`
model, you would create a migration to add the `author_id` column to the `books`
table:

```bash
rails generate migration AddAuthorToBooks author:references
```

This migration will add the `author_id` column and set up the foreign key
relationship in the database, ensuring that your models and database stay in
sync.

To learn more about the different types of associations, you can read the next
section of this guide. Following that, you'll find some tips and tricks for
working with associations. Finally, there's a complete reference to the methods
and options for associations in Rails.

Types of Associations
---------------------

Rails supports six types of associations, each with a particular use-case in
mind.

Here is a list of all of the supported types with a link to their API docs for
more detailed information on how to use them, their method parameters, etc.

* [`belongs_to`][]
* [`has_one`][]
* [`has_many`][]
* [`has_many :through`][`has_many`]
* [`has_one :through`][`has_one`]
* [`has_and_belongs_to_many`][]

In the remainder of this guide, you'll learn how to declare and use the various
forms of associations. First, let's take a quick look at the situations where
each association type is appropriate.

[`belongs_to`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to
[`has_and_belongs_to_many`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many
[`has_many`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many
[`has_one`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one

### `belongs_to`

A [`belongs_to`][] association sets up a relationship 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:

```ruby
class Book < ApplicationRecord
  belongs_to :author
end
```

![belongs_to Association Diagram](images/association_basics/belongs_to.png)

NOTE: A `belongs_to` association _must_ use the singular term. If you use the
plural form, like `belongs_to :authors` in the `Book` model, and try to create a
book with `Book.create(authors: @author)`, Rails will give you an "uninitialized
constant Book::Authors" error. This happens because Rails automatically infers
the class name from the association name. If the association name is `:authors`,
Rails will look for a class named `Authors` instead of `Author`.

The corresponding migration might look like this:

```ruby
class CreateBooks < ActiveRecord::Migration[7.2]
  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
```

In database terms, the `belongs_to` association says that this model's table
contains a column which represents a reference to another table. This can be
used to set up one-to-one or one-to-many relations, depending on the setup. If
the table _of the other class_ contains the reference in a one-to-one relation,
then you should use `has_one` instead.

When used alone, `belongs_to` produces a one-directional one-to-one
relationship. Therefore each book in the above example "knows" its author, but
the authors don't know about their books. To setup a [bi-directional
association](#bi-directional-associations) - use `belongs_to` in combination
with a `has_one` or `has_many` on the other model, in this case the Author
model.

NOTE: By default `belongs_to` validates the presence of the associated record to
guarantee reference consistency.<br/><br/>If `optional` is set to true in the
model, then `belongs_to` does not guarantee reference consistency. This means
that the foreign key in one table might not reliably point to a valid primary
key in the referenced table.

```ruby
class Book < ApplicationRecord
  belongs_to :author, optional: true
end
```

Hence, depending on the use case, you might also need to add a database-level
foreign key constraint on the reference column, like this:

```ruby
create_table :books do |t|
  t.belongs_to :author, foreign_key: true
  # ...
end
```

This ensures that even though `optional: true` allows `author_id` to be NULL,
when it's not NULL, it must still reference a valid record in the authors table.

#### Methods Added by `belongs_to`

When you declare a `belongs_to` association, the declaring class automatically
gains numerous methods related to the association. Some of these are:

* `association=(associate)`
* `build_association(attributes = {})`
* `create_association(attributes = {})`
* `create_association!(attributes = {})`
* `reload_association`
* `reset_association`
* `association_changed?`
* `association_previously_changed?`

We'll discuss some of the common methods, but you can find an exhaustive list in
the [ActiveRecord Associations
API](https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to).

In all of the above methods, `association` is replaced with the symbol passed as
the first argument to `belongs_to`. For example, given the declaration:

```ruby
# app/models/book.rb
class Book < ApplicationRecord
  belongs_to :author
end

# app/models/author.rb
class Author < ApplicationRecord
  has_many :books
  validates :name, presence: true
end
```

An instance of the `Book` model will have the following methods:

* `author`
* `author=`
* `build_author`
* `create_author`
* `create_author!`
* `reload_author`
* `reset_author`
* `author_changed?`
* `author_previously_changed?`

NOTE: When initializing a new `has_one` or `belongs_to` association you must use
the `build_` prefix to build the association, rather than the
`association.build` method that would be used for `has_many` or
`has_and_belongs_to_many` associations. To create one, use the `create_` prefix.

##### Retrieving the association

The `association` method returns the associated object, if any. If no associated
object is found, it returns `nil`.

```ruby
@author = @book.author
```

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 `#reload_association` on the parent object.

```ruby
@author = @book.reload_author
```

To unload the cached version of the associated object—causing the next access,
if any, to query it from the database—call `#reset_association` on the parent
object.

```ruby
@book.reset_author
```

##### Assigning the Association

The `association=` 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.

```ruby
@book.author = @author
```


The `build_association` 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 _not_ yet
be saved.

```ruby
@author = @book.build_author(author_number: 123,
                             author_name: "John Doe")
```

The `create_association` method takes it a step further and also saves the
associated object once it passes all of the validations specified on the
associated model.

```ruby
@author = @book.create_author(author_number: 123,
                              author_name: "John Doe")
```

Finally, `create_association!` does the same, but raises
`ActiveRecord::RecordInvalid` if the record is invalid.

```ruby
# This will raise ActiveRecord::RecordInvalid because the name is blank
begin
  @book.create_author!(author_number: 123, name: "")
rescue ActiveRecord::RecordInvalid => e
  puts e.message
end
```

```irb
irb> raise_validation_error: Validation failed: Name can't be blank (ActiveRecord::RecordInvalid)
```

##### Checking for Association Changes

The `association_changed?` method returns true if a new associated object has
been assigned and the foreign key will be updated in the next save.

The `association_previously_changed?` method returns true if the previous save
updated the association to reference a new associate object.

```ruby
@book.author # => #<Author author_number: 123, author_name: "John Doe">
@book.author_changed? # => false
@book.author_previously_changed? # => false

@book.author = Author.second # => #<Author author_number: 456, author_name: "Jane Smith">
@book.author_changed? # => true

@book.save!
@book.author_changed? # => false
@book.author_previously_changed? # => true
```

NOTE: Do not confuse `model.association_changed?` with
`model.association.changed?`. The former checks if the association has been
replaced with a new record, while the latter tracks changes to the attributes of
the association.

##### Checking for Existing Associations

You can see if any associated objects exist by using the `association.nil?`
method:

```ruby
if @book.author.nil?
  @msg = "No author found for this book"
end
```

##### Saving Behavior of Associated Objects

Assigning an object to a `belongs_to` association does _not_ automatically save
either the current object or the associated object. However, when you save the
current object, the association is saved as well.

### `has_one`

A [`has_one`][] association indicates that one other model has a reference to
this model. That model can be fetched through this association.

For example, if each supplier in your application has only one account, you'd
declare the supplier model like this:

```ruby
class Supplier < ApplicationRecord
  has_one :account
end
```

The main difference from `belongs_to` is that the link column (in this case
`supplier_id`) is located in the other table, not the table where the `has_one`
is declared.

![has_one Association Diagram](images/association_basics/has_one.png)

The corresponding migration might look like this:

```ruby
class CreateSuppliers < ActiveRecord::Migration[7.2]
  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
```

The `has_one` association creates a one-to-one match with another model. In
database terms, this association says that the other class contains the foreign
key. If this class contains the foreign key, then you should use `belongs_to`
instead.

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. The unique
index ensures that each supplier is associated with only one account and allows
you to query in an efficient manner, while the foreign key constraint ensures
that the `supplier_id` in the `accounts` table refers to a valid `supplier` in
the `suppliers` table. This enforces the association at the database level.

```ruby
create_table :accounts do |t|
  t.belongs_to :supplier, index: { unique: true }, foreign_key: true
  # ...
end
```

This relation can be [bi-directional](#bi-directional-associations) when used in
combination with `belongs_to` on the other model.

#### Methods Added by [`has_one`](#has-one)

When you declare a `has_one` association,  the declaring class automatically
gains numerous methods related to the association. Some of these are:

* `association`
* `association=(associate)`
* `build_association(attributes = {})`
* `create_association(attributes = {})`
* `create_association!(attributes = {})`
* `reload_association`
* `reset_association`

We'll discuss some of the common methods, but you can find an exhaustive list in
the [ActiveRecord Associations
API](https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one).

Like with the [`belongs_to` references](#methods-added-by-belongs-to), in all of
these methods, `association` is replaced with the symbol passed as the first
argument to `has_one`. For example, given the declaration:

```ruby
# app/models/supplier.rb
class Supplier < ApplicationRecord
  has_one :account
end

# app/models/account.rb
class Account < ApplicationRecord
  validates :terms, presence: true
  belongs_to :supplier
end
```

Each instance of the `Supplier` model will have these methods:

* `account`
* `account=`
* `build_account`
* `create_account`
* `create_account!`
* `reload_account`
* `reset_account`

NOTE: When initializing a new `has_one` or `belongs_to` association you must use
the `build_` prefix to build the association, rather than the
`association.build` method that would be used for `has_many` or
`has_and_belongs_to_many` associations. To create one, use the `create_` prefix.

##### Retrieving the association

The `association` method returns the associated object, if any. If no associated
object is found, it returns `nil`.

```ruby
@account = @supplier.account
```

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 `#reload_association` on the parent object.

```ruby
@account = @supplier.reload_account
```

To unload the cached version of the associated object—forcing the next access,
if any, to query it from the database—call `#reset_association` on the parent
object.

```ruby
@supplier.reset_account
```

##### Assigning the Association

The `association=` method assigns an associated object to this object. Behind
the scenes, this means extracting the primary key from this object and setting
the associated object's foreign key to the same value.

```ruby
@supplier.account = @account
```


The `build_association` method returns a new object of the associated type. This
object will be instantiated from the passed attributes, and the link through
this objects foreign key will be set, but the associated object will _not_ yet
be saved.

```ruby
@account = @supplier.build_account(terms: "Net 30")
```

The `create_association` method takes it a step further and also saves the
associated object once it passes all of the validations specified on the
associated model.

```ruby
@account = @supplier.create_account(terms: "Net 30")
```

Finally, `create_association!` does the same as `create_association` above,
but raises `ActiveRecord::RecordInvalid` if the record is invalid.

```ruby
# This will raise ActiveRecord::RecordInvalid because the terms is blank
begin
  @supplier.create_account!(terms: "")
rescue ActiveRecord::RecordInvalid => e
  puts e.message
end
```

```irb
irb> raise_validation_error: Validation failed: Terms can't be blank (ActiveRecord::RecordInvalid)
```

##### Checking for Existing Associations

You can see if any associated objects exist by using the `association.nil?`
method:

```ruby
if @supplier.account.nil?
  @msg = "No account found for this supplier"
end
```

##### Saving Behavior of Associated Objects

When you assign an object to a `has_one` association, that object is
automatically saved to update its foreign key. Additionally, any object being
replaced is also automatically saved, as its foreign key will change too.

If either of these saves fails due to validation errors, the assignment
statement returns `false`, and the assignment itself is canceled.

If the parent object (the one declaring the `has_one` association) is unsaved
(that is, `new_record?` returns `true`) then the child objects are not saved
immediately. They will be automatically saved when the parent object is saved.

If you want to assign an object to a `has_one` association without saving the
object, use the `build_association` method. This method creates a new, unsaved
instance of the associated object, allowing you to work with it before deciding
to save it.

Use `autosave: false` when you want to control the saving behavior of the
associated objects for the model. This setting prevents the associated object
from being saved automatically when the parent object is saved. In contrast, use
`build_association` when you need to work with an unsaved associated object and
delay its persistence until you're ready.

### `has_many`

A [`has_many`][] association is similar to `has_one`, but indicates a
one-to-many relationship with another model. You'll often find this association
on the "other side" of a `belongs_to` 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:

```ruby
class Author < ApplicationRecord
  has_many :books
end
```

`has_many` establishes a one-to-many relationship between models, allowing each
instance of the declaring model (`Author`) to have multiple instances of the
associated model (`Book`).

NOTE: Unlike a `has_one` and `belongs_to` association, the name of the other
model is pluralized when declaring a `has_many` association.

![has_many Association Diagram](images/association_basics/has_many.png)

The corresponding migration might look like this:

```ruby
class CreateAuthors < ActiveRecord::Migration[7.2]
  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
```

The `has_many` association creates a one-to-many relationship with another
model. In database terms, this association says that the other class will have a
foreign key that refers to instances of this class.

In this migration, the `authors` table is created with a `name` column to store
the names of authors. The `books` table is also created, and it includes a
`belongs_to :author` association. This association establishes a foreign key
relationship between the `books` and `authors` tables. Specifically, the
`author_id` column in the `books` table acts as a foreign key, referencing the
`id` column in the `authors` table. By including this `belongs_to :author`
association in the `books` table, we ensure that each book is associated with a
single author, enabling a `has_many` association from the `Author` model. This
setup allows each author to have multiple associated books.

Depending on the use case, it's usually a good idea to create a non-unique index
and optionally a foreign key constraint on the author column for the books
table. Adding an index on the `author_id` column improves query performance when
retrieving books associated with a specific author.

If you wish to enforce [referential
integrity](https://en.wikipedia.org/wiki/Referential_integrity) at the database
level, add the [`foreign_key: true`](active_record_migrations.html#foreign-keys)
option to the `reference` column declarations above. This will ensure that the
`author_id` in the books table must correspond to a valid `id` in the `authors`
table,

```ruby
create_table :books do |t|
  t.belongs_to :author, index: true, foreign_key: true
  # ...
end
```

This relation can be [bi-directional](#bi-directional-associations) when used in
combination with `belongs_to` on the other model.

#### Methods Added by `has_many`

When you declare a `has_many` association, the declaring class gains numerous
methods related to the association. Some of these are:

* `collection`
* [`collection<<(object, ...)`][`collection<<`]
* [`collection.delete(object, ...)`][`collection.delete`]
* [`collection.destroy(object, ...)`][`collection.destroy`]
* `collection=(objects)`
* `collection_singular_ids`
* `collection_singular_ids=(ids)`
* [`collection.clear`][]
* [`collection.empty?`][]
* [`collection.size`][]
* [`collection.find(...)`][`collection.find`]
* [`collection.where(...)`][`collection.where`]
* [`collection.exists?(...)`][`collection.exists?`]
* [`collection.build(attributes = {})`][`collection.build`]
* [`collection.create(attributes = {})`][`collection.create`]
* [`collection.create!(attributes = {})`][`collection.create!`]
* [`collection.reload`][]

We'll discuss some of the common methods, but you can find an exhaustive list in
the [ActiveRecord Associations
API](https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many).

In all of these methods, `collection` is replaced with the symbol passed as the
first argument to `has_many`, and `collection_singular` is replaced with the
singularized version of that symbol. For example, given the declaration:

```ruby
class Author < ApplicationRecord
  has_many :books
end
```

An instance of the `Author` model can have the following methods:

```
books
books<<(object, ...)
books.delete(object, ...)
books.destroy(object, ...)
books=(objects)
book_ids
book_ids=(ids)
books.clear
books.empty?
books.size
books.find(...)
books.where(...)
books.exists?(...)
books.build(attributes = {}, ...)
books.create(attributes = {})
books.create!(attributes = {})
books.reload
```

[`collection<<`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-3C-3C
[`collection.build`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-build
[`collection.clear`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-clear
[`collection.create`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-create
[`collection.create!`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-create-21
[`collection.delete`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-delete
[`collection.destroy`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-destroy
[`collection.empty?`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-empty-3F
[`collection.exists?`]:
    https://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F
[`collection.find`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-find
[`collection.reload`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-reload
[`collection.size`]:
    https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-size
[`collection.where`]:
    https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-where

##### Managing the Collection

The `collection` method returns a Relation of all of the associated objects. If
there are no associated objects, it returns an empty Relation.

```ruby
@books = @author.books
```

The [`collection.delete`][] method removes one or more objects from the
collection by setting their foreign keys to `NULL`.

```ruby
@author.books.delete(@book1)
```

WARNING: Additionally, objects will be destroyed if they're associated with
`dependent: :destroy`, and deleted if they're associated with `dependent:
:delete_all`.

The [`collection.destroy`][] method removes one or more objects from the
collection by running `destroy` on each object.

```ruby
@author.books.destroy(@book1)
```

WARNING: Objects will _always_ be removed from the database, ignoring the
`:dependent` option.

The [`collection.clear`][] method removes all objects from the collection
according to the strategy specified by the `dependent` option. If no option is
given, it follows the default strategy. The default strategy for `has_many
:through` associations is `delete_all`, and for `has_many` associations is to
set the foreign keys to `NULL`.

```ruby
@author.books.clear
```

WARNING: Objects will be deleted if they're associated with `dependent:
:destroy` or `dependent: :destroy_async`, just like `dependent: :delete_all`.

The [`collection.reload`][] method returns a Relation of all of the associated
objects, forcing a database read. If there are no associated objects, it returns
an empty Relation.

```ruby
@books = @author.books.reload
```

##### Assigning the Collection

The `collection=(objects)` method makes the collection contain only the supplied
objects, by adding and deleting as appropriate. The changes are persisted to the
database.

The `collection_singular_ids=(ids)` method makes the collection contain only the
objects identified by the supplied primary key values, by adding and deleting as
appropriate. The changes are persisted to the database.

##### Querying the Collection

The `collection_singular_ids` method returns an array of the ids of the objects
in the collection.

```ruby
@book_ids = @author.book_ids
```

The [`collection.empty?`][] method returns `true` if the collection does not
contain any associated objects.

```erb
<% if @author.books.empty? %>
  No Books Found
<% end %>
```

The [`collection.size`][] method returns the number of objects in the
collection.

```ruby
@book_count = @author.books.size
```

The [`collection.find`][] method finds objects within the collection's table.

```ruby
@available_book = @author.books.find(1)
```

The [`collection.where`][] method finds objects within the collection based on
the conditions supplied but the objects are loaded lazily meaning that the
database is queried only when the object(s) are accessed.

```ruby
@available_books = @author.books.where(available: true) # No query yet
@available_book = @available_books.first # Now the database will be queried
```

The [`collection.exists?`][] method checks whether an object meeting the
supplied conditions exists in the collection's table.

##### Building and Creating Associated Objects

The [`collection.build`][] method returns a single or array of new objects of
the associated type. The object(s) will be instantiated from the passed
attributes, and the link through their foreign key will be created, but the
associated objects will _not_ yet be saved.

```ruby
@book = @author.books.build(published_at: Time.now,
                            book_number: "A12345")

@books = @author.books.build([
  { published_at: Time.now, book_number: "A12346" },
  { published_at: Time.now, book_number: "A12347" }
])
```

The [`collection.create`][] method returns a single or array of new objects of
the associated type. The object(s) will be instantiated from the passed
attributes, the link through its foreign key will be created, and, once it
passes all of the validations specified on the associated model, the associated
object _will_ be saved.

```ruby
@book = @author.books.create(published_at: Time.now,
                             book_number: "A12345")

@books = @author.books.create([
  { published_at: Time.now, book_number: "A12346" },
  { published_at: Time.now, book_number: "A12347" }
])
```

`collection.create!` does the same as `collection.create`, but raises
`ActiveRecord::RecordInvalid` if the record is invalid.

##### When are Objects Saved?

When you assign an object to a `has_many` association, that object is
automatically saved (in order to update its foreign key). If you assign multiple
objects in one statement, then they are all saved.

If any of these saves fails due to validation errors, then the assignment
statement returns `false` and the assignment itself is cancelled.

If the parent object (the one declaring the `has_many` association) is unsaved
(that is, `new_record?` returns `true`) then the child objects are not saved
when they are added. All unsaved members of the association will automatically
be saved when the parent is saved.

If you want to assign an object to a `has_many` association without saving the
object, use the `collection.build` method.

### `has_many :through`

A [`has_many :through`][`has_many`] association is often used to set up a
many-to-many relationship with another model. This association indicates that
the declaring model can be matched with zero or more instances of another model
by proceeding _through_ a third model.

For example, consider a medical practice where patients make appointments to see
physicians. The relevant association declarations could look like this:

```ruby
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
```

`has_many :through` establishes a many-to-many relationship between models,
allowing instances of one model (Physician) to be associated with multiple
instances of another model (Patient) through a third "join" model (Appointment).

![has_many :through Association
Diagram](images/association_basics/has_many_through.png)

The corresponding migration might look like this:

```ruby
class CreateAppointments < ActiveRecord::Migration[7.2]
  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
```

In this migration the `physicians` and `patients` tables are created with a
`name` column. The `appointments` table, which acts as the join table, is
created with `physician_id` and `patient_id` columns, establishing the
many-to-many relationship between `physicians` and `patients`.

You could also consider using a [composite primary
key](active_record_composite_primary_keys.html) for the join table in the
`has_many :through` relationship like below:

```ruby
class CreateAppointments < ActiveRecord::Migration[7.2]
  def change
    #  ...
    create_table :appointments, primary_key: [:physician_id, :patient_id] do |t|
      t.belongs_to :physician
      t.belongs_to :patient
      t.datetime :appointment_date
      t.timestamps
    end
  end
end
```

The collection of join models in a `has_many :through` association can be
managed using standard [`has_many` association
methods](#methods-added-by-has-many). For example, if you assign a list of
patients to a physician like this:

```ruby
physician.patients = patients
```

Rails will automatically create new join models for any patients in the new list
that were not previously associated with the physician. Additionally, if any
patients that were previously associated with the physician are not included in
the new list, their join records will be automatically deleted. This simplifies
managing many-to-many relationships by handling the creation and deletion of the
join models for you.

WARNING: Automatic deletion of join models is direct, no destroy callbacks are
triggered. You can read more about callbacks in the [Active Record Callbacks
Guide](active_record_callbacks.html).

The `has_many :through` association is also useful for setting up "shortcuts"
through nested `has_many` associations. This is particularly beneficial when you
need to access a collection of related records through an intermediary
association.

For example, if a document has many sections, and each section has many
paragraphs, you may sometimes want to get a simple collection of all paragraphs
in the document without having to manually traverse through each section.

You can set this up with a `has_many :through` association as follows:

```ruby
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
```

With `through: :sections` specified, Rails will now understand:

```ruby
@document.paragraphs
```

Whereas, if you had not set up a `has_many :through` association, you would have
needed to do something like this to get paragraphs in a document:

```ruby
paragraphs = []
@document.sections.each do |section|
  paragraphs.concat(section.paragraphs)
end
```

### `has_one :through`

A [`has_one :through`][`has_one`] association sets up a one-to-one relationship
with another model through an intermediary model. This association indicates
that the declaring model can be matched with one instance of another model by
proceeding _through_ 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:

```ruby
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
```

This setup allows a `supplier` to directly access its `account_history` through
its `account`.

![has_one :through Association
Diagram](images/association_basics/has_one_through.png)

The corresponding migration to set up these associations might look like this:

```ruby
class CreateAccountHistories < ActiveRecord::Migration[7.2]
  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
```

### `has_and_belongs_to_many`

A [`has_and_belongs_to_many`][] association creates a direct many-to-many
relationship with another model, with no intervening model. This association
indicates that each instance of the declaring model refers to zero or more
instances of another model.

For example, consider an application with `Assembly` and `Part` models, where
each assembly can contain many parts, and each part can be used in many
assemblies. You can set up the models as follows:

```ruby
class Assembly < ApplicationRecord
  has_and_belongs_to_many :parts
end

class Part < ApplicationRecord
  has_and_belongs_to_many :assemblies
end
```

![has_and_belongs_to_many Association
Diagram](images/association_basics/habtm.png)

Even though a `has_and_belongs_to_many` does not require an intervening model,
it does require a separate table to establish the many-to-many relationship
between the two models involved. This intervening table serves to store the
related data, mapping the associations between instances of the two models. The
table does not necessarily need a primary key since its purpose is solely to
manage the relationship between the associated records. The corresponding
migration might look like this:

```ruby
class CreateAssembliesAndParts < ActiveRecord::Migration[7.2]
  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 a join table to establish the many-to-many relationship between assemblies and parts.
    # `id: false` indicates that the table does not need a primary key of its own
    create_table :assemblies_parts, id: false do |t|
      # creates foreign keys linking the join table to the `assemblies` and `parts` tables
      t.belongs_to :assembly
      t.belongs_to :part
    end
  end
end
```

The `has_and_belongs_to_many` association creates a many-to-many relationship
with another model. In database terms, this associates two classes via an
intermediate join table that includes foreign keys referring to each of the
classes.

If the join table for a `has_and_belongs_to_many` association has additional
columns beyond the two foreign keys, these columns will be added as attributes
to records retrieved via that association. Records returned with additional
attributes will always be read-only, because Rails cannot save changes to those
attributes.

WARNING: The use of extra attributes on the join table in a
`has_and_belongs_to_many` association is deprecated. If you require this sort of
complex behavior on the table that joins two models in a many-to-many
relationship, you should use a `has_many :through` association instead of
`has_and_belongs_to_many`.

#### Methods Added by `has_and_belongs_to_many`

When you declare a `has_and_belongs_to_many` association, the declaring class
gains numerous methods related to the association. Some of these are:

* `collection`
* [`collection<<(object, ...)`][`collection<<`]
* [`collection.delete(object, ...)`][`collection.delete`]
* [`collection.destroy(object, ...)`][`collection.destroy`]
* `collection=(objects)`
* `collection_singular_ids`
* `collection_singular_ids=(ids)`
* [`collection.clear`][]
* [`collection.empty?`][]
* [`collection.size`][]
* [`collection.find(...)`][`collection.find`]
* [`collection.where(...)`][`collection.where`]
* [`collection.exists?(...)`][`collection.exists?`]
* [`collection.build(attributes = {})`][`collection.build`]
* [`collection.create(attributes = {})`][`collection.create`]
* [`collection.create!(attributes = {})`][`collection.create!`]
* [`collection.reload`][]

We'll discuss some of the common methods, but you can find an exhaustive list in
the [ActiveRecord Associations
API](https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many).

In all of these methods, `collection` is replaced with the symbol passed as the
first argument to `has_and_belongs_to_many`, and `collection_singular` is
replaced with the singularized version of that symbol. For example, given the
declaration:

```ruby
class Part < ApplicationRecord
  has_and_belongs_to_many :assemblies
end
```

An instance of the `Part` model can have the following methods:

```
assemblies
assemblies<<(object, ...)
assemblies.delete(object, ...)
assemblies.destroy(object, ...)
assemblies=(objects)
assembly_ids
assembly_ids=(ids)
assemblies.clear
assemblies.empty?
assemblies.size
assemblies.find(...)
assemblies.where(...)
assemblies.exists?(...)
assemblies.build(attributes = {}, ...)
assemblies.create(attributes = {})
assemblies.create!(attributes = {})
assemblies.reload
```

##### Managing the Collection

The `collection` method returns a Relation of all of the associated objects. If
there are no associated objects, it returns an empty Relation.

```ruby
@assemblies = @part.assemblies
```

The [`collection<<`][] method adds one or more objects to the collection by
creating records in the join table.

```ruby
@part.assemblies << @assembly1
```

NOTE: This method is aliased as `collection.concat` and `collection.push`.

The [`collection.delete`][] method removes one or more objects from the
collection by deleting records in the join table. This does not destroy the
objects.

```ruby
@part.assemblies.delete(@assembly1)
```

The [`collection.destroy`][] method removes one or more objects from the
collection by deleting records in the join table. This does not destroy the
objects.

```ruby
@part.assemblies.destroy(@assembly1)
```

The [`collection.clear`][] method removes every object from the collection by
deleting the rows from the joining table. This does not destroy the associated
objects.


##### Assigning the Collection

The `collection=` method makes the collection contain only the supplied objects,
by adding and deleting as appropriate. The changes are persisted to the
database.

The `collection_singular_ids=` method makes the collection contain only the
objects identified by the supplied primary key values, by adding and deleting as
appropriate. The changes are persisted to the database.

##### Querying the Collection

The `collection_singular_ids` method returns an array of the ids of the objects
in the collection.

```ruby
@assembly_ids = @part.assembly_ids
```

The [`collection.empty?`][] method returns `true` if the collection does not
contain any associated objects.

```html+erb
<% if @part.assemblies.empty? %>
  This part is not used in any assemblies
<% end %>
```

The [`collection.size`][] method returns the number of objects in the
collection.

```ruby
@assembly_count = @part.assemblies.size
```

The [`collection.find`][] method finds objects within the collection's table.

```ruby
@assembly = @part.assemblies.find(1)
```

The [`collection.where`][] method finds objects within the collection based on
the conditions supplied but the objects are loaded lazily meaning that the
database is queried only when the object(s) are accessed.

```ruby
@new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago)
```

The [`collection.exists?`][] method checks whether an object meeting the
supplied conditions exists in the collection's table.


##### Building and Creating Associated Objects

The [`collection.build`][] method returns a new object of the associated type.
This object will be instantiated from the passed attributes, and the link
through the join table will be created, but the associated object will _not_ yet
be saved.

```ruby
@assembly = @part.assemblies.build({ assembly_name: "Transmission housing" })
```

The [`collection.create`][] method returns a new object of the associated type.
This object will be instantiated from the passed attributes, the link through
the join table will be created, and, once it passes all of the validations
specified on the associated model, the associated object _will_ be saved.

```ruby
@assembly = @part.assemblies.create({ assembly_name: "Transmission housing" })
```

Does the same as `collection.create`, but raises `ActiveRecord::RecordInvalid`
if the record is invalid.

The [`collection.reload`][] method returns a Relation of all of the associated
objects, forcing a database read. If there are no associated objects, it returns
an empty Relation.

```ruby
@assemblies = @part.assemblies.reload
```

##### When are Objects Saved?

When you assign an object to a `has_and_belongs_to_many` association, that
object is automatically saved (in order to update the join table). If you assign
multiple objects in one statement, then they are all saved.

If any of these saves fails due to validation errors, then the assignment
statement returns `false` and the assignment itself is cancelled.

If the parent object (the one declaring the `has_and_belongs_to_many`
association) is unsaved (that is, `new_record?` returns `true`) then the child
objects are not saved when they are added. All unsaved members of the
association will automatically be saved when the parent is saved.

If you want to assign an object to a `has_and_belongs_to_many` association
without saving the object, use the `collection.build` method.

Choosing an Association
-----------------------

### `belongs_to` vs `has_one`

If you want to set up a one-to-one relationship between two models, you can
choose between a `belongs_to` and a `has_one` association. How do you know which
one to choose?


The distinction lies in the placement of the foreign key, which goes on the
table of the class declaring the `belongs_to` association. However, it’s
essential to understand the semantics to determine the correct associations:

- `belongs_to`: This association indicates that the current model contains the
  foreign key and is a child in the relationship. It references another model,
  implying that each instance of this model is linked to one instance of the
  other model.
- `has_one`: This association indicates that the current model is the parent in
  the relationship, and it owns one instance of the other model.

For example, consider a scenario with suppliers and their accounts. It makes
more sense to say that a supplier has/owns an account (where the supplier is the
parent) rather than an account has/owns a supplier. Therefore, the correct
associations would be:

- A supplier has one account.
- An account belongs to one supplier.

Here is how you can define these associations in Rails:

```ruby
class Supplier < ApplicationRecord
  has_one :account
end

class Account < ApplicationRecord
  belongs_to :supplier
end
```

To implement these associations, you'll need to create the corresponding
database tables and set up the foreign key. Here's an example migration:

```ruby
class CreateSuppliers < ActiveRecord::Migration[7.2]
  def change
    create_table :suppliers do |t|
      t.string :name
      t.timestamps
    end

    create_table :accounts do |t|
      t.belongs_to :supplier_id
      t.string :account_number
      t.timestamps
    end

    add_index :accounts, :supplier_id
  end
end
```

Remember that the foreign key goes on the table of the class declaring the
belongs_to association. In this case the `account` table.

### `has_many :through` vs `has_and_belongs_to_many`

Rails offers two different ways to declare a many-to-many relationship between
models: `has_many :through` and `has_and_belongs_to_many`. Understanding the
differences and use cases for each can help you choose the best approach for
your application's needs.

The `has_many :through` association sets up a many-to-many relationship through
an intermediary model (also known as a join model). This approach is more
flexible and allows you to add validations, callbacks, and extra attributes to
the join model. The join table needs a `primary_key` (or a [composite primary
key](active_record_composite_primary_keys.html)).

```ruby
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
```

You'd use `has_many :through` when:

- You need to add extra attributes or methods to the join table.
- You require [validations](active_record_validations.html) or
  [callbacks](active_record_callbacks.html) on the join model.
- The join table should be treated as an independent entity with its own
  behavior.

The `has_and_belongs_to_many` association allows you to create a many-to-many
relationship directly between two models without needing an intermediary model.
This method is straightforward and is suitable for simple associations where no
additional attributes or behaviors are required on the join table. For
`has_and_belongs_to_many` associations, you'll need to create a join table
without a primary key.

```ruby
class Assembly < ApplicationRecord
  has_and_belongs_to_many :parts
end

class Part < ApplicationRecord
  has_and_belongs_to_many :assemblies
end
```

You'd use `has_and_belongs_to_many` when:

- The association is simple and does not require additional attributes or
  behaviors on the join table.
- You do not need validations, callbacks, or extra methods on the join table.

Advanced Associations
-------------------------

### Polymorphic Associations

A slightly more advanced twist on associations is the _polymorphic association_.
Polymorphic associations in Rails allow a model to belong to multiple other
models through a single association. This can be particularly useful when you
have a model that needs to be linked to different types of models.

For instance, imagine you have a `Picture` model that can belong to **either**
an `Employee` or a `Product`, because each of these can have a profile picture.
Here's how this could be declared:

```ruby
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
```

![Polymorphic Association Diagram](images/association_basics/polymorphic.png)

In the context above, `imageable` is a name chosen for the association. It's a
symbolic name that represents the polymorphic association between the `Picture`
model and other models such as `Employee` and `Product`. The important thing is
to use the same name (`imageable`) consistently across all associated models to
establish the polymorphic association correctly.

When you declare `belongs_to :imageable, polymorphic: true` in the `Picture`
model, you're saying that a `Picture` can belong to any model (like `Employee`
or `Product`) through this association.

You can think of a polymorphic `belongs_to` declaration as setting up an
interface that any other model can use. This allows you to retrieve a collection
of pictures from an instance of the `Employee` model using `@employee.pictures`.
Similarly, you can retrieve a collection of pictures from an instance of the
`Product` model using `@product.pictures`.

Additionally, if you have an instance of the `Picture` model, you can get its
parent via `@picture.imageable`, which could be an `Employee` or a `Product`.

To setup a polymorphic association manually you would need to declare both a
foreign key column (`imageable_id`) and a type column (`imageable_type`) in the
model:

```ruby
class CreatePictures < ActiveRecord::Migration[7.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
```

In our example, `imageable_id` could be the ID of either an `Employee` or a
`Product`, and `imageable_type` is the name of the associated model's class, so
either `Employee` or `Product`.

While creating the polymorphic association manually is acceptable, it is instead
recommended to use `t.references` or its alias `t.belong_to` and specify
`polymorphic: true` so that Rails knows that the association is polymorphic, and
it automatically adds both the foreign key and type columns to the table.

```ruby
class CreatePictures < ActiveRecord::Migration[7.2]
  def change
    create_table :pictures do |t|
      t.string :name
      t.belongs_to :imageable, polymorphic: true
      t.timestamps
    end
  end
end
```

WARNING: Since polymorphic associations rely on storing class names in the
database, that data must remain synchronized with the class name used by the
Ruby code. When renaming a class, make sure to update the data in the
polymorphic type column.

For example, if you change the class name from `Product` to `Item` then you'd
need to run a migration script to update the `imageable_type` column in the
`pictures` table (or whichever table is affected) with the new class name.
Additionally, you'll need to update any other references to the class name
throughout your application code to reflect the change.

### Models with Composite Primary Keys

Rails can often infer primary key-foreign key relationships between associated
models, but when dealing with composite primary keys, Rails typically defaults
to using only part of the composite key, often the id column, unless explicitly
instructed otherwise.

If you're working with composite primary keys in your Rails models and need to
ensure the correct handling of associations, please refer to the [Associations
section of the Composite Primary Keys
guide](active_record_composite_primary_keys#associations-between-models-with-composite-primary-keys).
This section provides comprehensive guidance on setting up and using
associations with composite primary keys in Rails, including how to specify
composite foreign keys when necessary.

### Self Joins

A self-join is a regular join, but the table is joined with itself. This is
useful in situations where there is a hierarchical relationship within a single
table. A common example is an employee management system where an employee can
have a manager, and that manager is also an employee.

Consider an organization where employees can be managers of other employees. We
want to track this relationship using a single `employees` table.

In your Rails model, you define the `Employee` class to reflect these
relationships:

```ruby
class Employee < ApplicationRecord
  # an employee can have many subordinates.
  has_many :subordinates, class_name: "Employee", foreign_key: "manager_id"

  # an employee can have one manager.
  belongs_to :manager, class_name: "Employee", optional: true
end
```

`has_many :subordinates` sets up a one-to-many relationship where an employee
can have many subordinates. Here, we specify that the related model is also
`Employee` (`class_name: "Employee"`) and the foreign key used to identify the
manager is `manager_id`.

`belongs_to :manager` sets up a one-to-one relationship where an employee can
belong to one manager. Again, we specify the related model as `Employee`.

To support this relationship, we need to add a `manager_id` column to the
`employees` table. This column references the `id` of another employee (the
manager).

```ruby
class CreateEmployees < ActiveRecord::Migration[7.2]
  def change
    create_table :employees do |t|
      # Add a belongs_to reference to the manager, which is an employee.
      t.belongs_to :manager, foreign_key: { to_table: :employees }
      t.timestamps
    end
  end
end
```

- `t.belongs_to :manager` adds a `manager_id` column to the `employees` table.
- `foreign_key: { to_table: :employees }` ensures that the `manager_id` column
  references the `id` column of the `employees` table.

NOTE: The `to_table` option passed to `foreign_key` and more are explained in
[`SchemaStatements#add_reference`][connection.add_reference].

With this setup, you can easily access an employee's subordinates and manager in
your Rails application.

To get an employee's subordinates:

```ruby
employee = Employee.find(1)
subordinates = employee.subordinates
```

To get an employee's manager:

```ruby
manager = employee.manager
```

[connection.add_reference]:
    https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_reference

Single Table Inheritance (STI)
------------------------------

Single Table Inheritance (STI) is a pattern in Rails that allows multiple models
to be stored in a single database table. This is useful when you have different
types of entities that share common attributes and behavior but also have
specific behaviors.

For example, suppose we have `Car`, `Motorcycle`, and `Bicycle` models. These
models will share fields like `color` and `price`, but each will have unique
behaviors. They will also each have their own controller.

### Generating the Base Vehicle Model

First, we generate the base `Vehicle` model with shared fields:

```bash
$ bin/rails generate model vehicle type:string color:string price:decimal{10.2}
```

Here, the `type` field is crucial for STI as it stores the model name (`Car`,
`Motorcycle`, or `Bicycle`). STI requires this field to differentiate between
the different models stored in the same table.

### Generating Child Models

Next, we generate the `Car`, `Motorcycle`, and `Bicycle` models that inherit
from Vehicle. These models won't have their own tables; instead, they will use
the `vehicles` table.

To generate the`Car` model:

```bash
$ bin/rails generate model car --parent=Vehicle
```

For this, we can use the `--parent=PARENT` option, which will generate a model
that inherits from the specified parent and without equivalent migration (since
the table already exists).

This generates a `Car` model that inherits from `Vehicle`:

```ruby
class Car < Vehicle
end
```

This means that all behavior added to Vehicle is available for Car too, as
associations, public methods, etc. Creating a car will save it in the `vehicles`
table with "Car" as the `type` field:

Repeat the same process for `Motorcycle` and `Bicycle`.

### Creating Records

Creating a record for `Car`:

```ruby
Car.create(color: 'Red', price: 10000)
```

This will generate the following SQL:

```sql
INSERT INTO "vehicles" ("type", "color", "price") VALUES ('Car', 'Red', 10000)
```

### Querying Records

Querying car records will search only for vehicles that are cars:

```ruby
Car.all
```

will run a query like:

```sql
SELECT "vehicles".* FROM "vehicles" WHERE "vehicles"."type" IN ('Car')
```

### Adding Specific Behavior

You can add specific behavior or methods to the child models. For example,
adding a method to the `Car` model:

```ruby
class Car < Vehicle
  def honk
    'Beep Beep'
  end
end
```

Now you can call the `honk` method on a `Car` instance:

```ruby
car = Car.first
car.honk
# => 'Beep Beep'
```

### Controllers

Each model can have its own controller. For example, the `CarsController`:

```ruby
# app/controllers/cars_controller.rb

class CarsController < ApplicationController
  def index
    @cars = Car.all
  end
end
```

### Overriding the inheritance column

There may be cases (like when working with a legacy database) where you need to
override the name of the inheritance column. This can be achieved with the
[inheritance_column][] method.

```ruby
# Schema: vehicles[ id, kind, created_at, updated_at ]
class Vehicle < ApplicationRecord
  self.inheritance_column = "kind"
end

class Car < Vehicle
end

Car.create
# => #<Car kind: "Car", color: "Red", price: 10000>
```

In this setup, Rails will use the `kind` column to store the model type,
allowing STI to function correctly with the custom column name.

### Disabling the inheritance column

There may be cases (like when working with a legacy database) where you need to
disable Single Table Inheritance altogether. If you don't disable STI properly,
you might encounter an [`ActiveRecord::SubclassNotFound`][] error.

To disable STI, you can set the [inheritance_column][] to `nil`.

```ruby
# Schema: vehicles[ id, type, created_at, updated_at ]
class Vehicle < ApplicationRecord
  self.inheritance_column = nil
end

Vehicle.create!(type: "Car")
# => #<Vehicle type: "Car", color: "Red", price: 10000>
```

In this configuration, Rails will treat the type column as a normal attribute
and will not use it for STI purposes. This is useful if you need to work with a
legacy schema that does not follow the STI pattern.

These adjustments provide flexibility when integrating Rails with existing
databases or when specific customization is required for your models.

[inheritance_column]:
    https://api.rubyonrails.org/classes/ActiveRecord/ModelSchema.html#method-c-inheritance_column
[`ActiveRecord::SubclassNotFound`]:
    https://api.rubyonrails.org/classes/ActiveRecord/SubclassNotFound.html

### Considerations

[`Single Table Inheritance (STI)`](#single-table-inheritance-sti) works best
when there is little difference between subclasses and their attributes, but it
includes all attributes of all subclasses in a single table.

A disadvantage of this approach is that it can result in table bloat, as the
table will include attributes specific to each subclass, even if they aren't
used by others. This can be solved by using [`Delegated
Types`](#delegated-types).

Additionally, if you’re using [polymorphic
associations](#polymorphic-associations), where a model can belong to more than
one other model via a type and an ID, it could become complex to maintain
referential integrity because the association logic must handle different types
correctly.

Finally, if you have specific data integrity checks or validations that differ
between subclasses, you need to ensure these are correctly handled by Rails or
the database, especially when setting up foreign key constraints.

Delegated Types
----------------

Delegated types solves the [`Single Table Inheritance
(STI)`](#single-table-inheritance-sti) problem of table bloat via
`delegated_type`. This approach allows us to store shared attributes in a
superclass table and have separate tables for subclass-specific attributes.

### Setting up Delegated Types

To use delegated types, we need to model our data as follows:

* There is a superclass that stores shared attributes among all subclasses in
  its table.
* Each subclass must inherit from the superclass, and will have a separate table
  for any additional attributes specific to it.

This eliminates the need to define attributes in a single table that are
unintentionally shared among all subclasses.

### Generating Models

In order to apply this to our example above, we need to regenerate our models.

First, let's generate the base `Entry` model which will act as our superclass:

```bash
$ bin/rails generate model entry entryable_type:string entryable_id:integer
```

Then, we will generate new `Message` and `Comment` models for delegation:

```bash
$ bin/rails generate model message subject:string body:string
$ bin/rails generate model comment content:string
```

After running the generators, our models should look like this:

```ruby
# Schema: entries[ id, entryable_type, entryable_id, created_at, updated_at ]
class Entry < ApplicationRecord
end

# Schema: messages[ id, subject, body, created_at, updated_at ]
class Message < ApplicationRecord
end

# Schema: comments[ id, content, created_at, updated_at ]
class Comment < ApplicationRecord
end
```

### Declaring `delegated_type`

First, declare a `delegated_type` in the superclass `Entry`.

```ruby
class Entry < ApplicationRecord
  delegated_type :entryable, types: %w[ Message Comment ], dependent: :destroy
end
```

The `entryable` parameter specifies the field to use for delegation, and include
the types `Message` and `Comment` as the delegate classes. The `entryable_type`
and `entryable_id` fields store the subclass name and the record ID of the
delegate subclass, respectively.

### Defining the `Entryable` Module

Next, define a module to implement those delegated types by declaring the `as:
:entryable` parameter in the `has_one` association.

```ruby
module Entryable
  extend ActiveSupport::Concern

  included do
    has_one :entry, as: :entryable, touch: true
  end
end
```

Include the created module in your subclass:

```ruby
class Message < ApplicationRecord
  include Entryable
end

class Comment < ApplicationRecord
  include Entryable
end
```

With this definition complete, our `Entry` delegator now provides the following
methods:

| Method                  | Return                                                                          |
| ----------------------- | ------------------------------------------------------------------------------- |
| `Entry.entryable_types` | ["Message", "Comment"]                                                          |
| `Entry#entryable_class` | Message or Comment                                                              |
| `Entry#entryable_name`  | "message" or "comment"                                                          |
| `Entry.messages`        | `Entry.where(entryable_type: "Message")`                                        |
| `Entry#message?`        | Returns true when `entryable_type == "Message"`                                 |
| `Entry#message`         | Returns the message record, when `entryable_type == "Message"`, otherwise `nil` |
| `Entry#message_id`      | Returns `entryable_id`, when `entryable_type == "Message"`, otherwise `nil`     |
| `Entry.comments`        | `Entry.where(entryable_type: "Comment")`                                        |
| `Entry#comment?`        | Returns true when `entryable_type == "Comment"`                                 |
| `Entry#comment`         | Returns the comment record, when `entryable_type == "Comment"`, otherwise `nil` |
| `Entry#comment_id`      | Returns entryable_id, when `entryable_type == "Comment"`, otherwise `nil`       |

### Object creation

When creating a new `Entry` object, we can specify the `entryable` subclass at
the same time.

```ruby
Entry.create! entryable: Message.new(subject: "hello!")
```

### Adding further delegation

We can enhance our `Entry` delegator by defining `delegate` and using
polymorphism on the subclasses. For example, to delegate the `title` method from
`Entry` to it's subclasses:

```ruby
class Entry < ApplicationRecord
  delegated_type :entryable, types: %w[ Message Comment ]
  delegate :title, to: :entryable
end

class Message < ApplicationRecord
  include Entryable

  def title
    subject
  end
end

class Comment < ApplicationRecord
  include Entryable

  def title
    content.truncate(20)
  end
end
```

This setup allows `Entry` to delegate the `title` method to its subclasses,
where `Message` uses `subject` and `Comment` uses a truncated version of
`content`.

Tips, Tricks, and Warnings
--------------------------

Here are a few things you should know to make efficient use of Active Record
associations in your Rails applications:

* Controlling caching
* Avoiding name collisions
* Updating the schema
* Controlling association scope
* Bi-directional associations

### Controlling Association Caching

All of the association methods are built around caching, which keeps the result
of loaded associations for further operations. The cache is even shared across
methods. For example:

```ruby
# retrieves books from the database
author.books.load

# uses the cached copy of books
author.books.size

# uses the cached copy of books
author.books.empty?
```

NOTE: When we use `author.books`, the data is not immediately loaded from the
database. Instead, it sets up a query that will be executed when you actually
try to use the data, for example, by calling methods that require data like
each, size, empty?, etc. By calling `author.books.load`, before calling other
methods which use the data, you explicitly trigger the query to load the data
from the database immediately. This is useful if you know you will need the data
and want to avoid the potential performance overhead of multiple queries being
triggered as you work with the association.

But what if you want to reload the cache, because data might have been changed
by some other part of the application? Just call
[`reload`](https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-reload)
on the association:

```ruby
# retrieves books from the database
author.books.load

# uses the cached copy of books
author.books.size

# discards the cached copy of books and goes back to the database
author.books.reload.empty?
```

### Avoiding Name Collisions

When creating associations in Ruby on Rails models, it's important to avoid
using names that are already used for instance methods of `ActiveRecord::Base`.
This is because creating an association with a name that clashes with an
existing method could lead to unintended consequences, such as overriding the
base method and causing issues with functionality. For example, using names like
`attributes` or `connection` for associations would be problematic.

### Updating the Schema

Associations are extremely useful, they are responsible for defining the
relationships between models but they do not update your database schema. You
are responsible for maintaining your database schema to match your associations.
This usually involves two main tasks: creating foreign keys for [`belongs_to`
associations](#belongs-to) and setting up the correct join table for [`has_many
:through`](#has-many-through) and
[`has_and_belongs_to_many`](#has-and-belongs-to-many) associations. You can read
more about when to use a `has_many :through vs has_and_belongs_to_many` [in the
has many through vs has and belongs to many
section](#has-many-through-vs-has-and-belongs-to-many).

#### Creating Foreign Keys for `belongs_to` Associations

When you declare a [`belongs_to` association](#belongs-to), you need to create
foreign keys as appropriate. For example, consider this model:

```ruby
class Book < ApplicationRecord
  belongs_to :author
end
```

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:

```ruby
class CreateBooks < ActiveRecord::Migration[7.2]
  def change
    create_table :books do |t|
      t.datetime   :published_at
      t.string     :book_number
      t.belongs_to :author
    end
  end
end
```

Whereas for an existing table, it might look like this:

```ruby
class AddAuthorToBooks < ActiveRecord::Migration[7.2]
  def change
    add_reference :books, :author
  end
end
```

#### Creating Join Tables for `has_and_belongs_to_many` Associations

If you create a `has_and_belongs_to_many` association, you need to explicitly
create the join table. Unless the name of the join table is explicitly specified
by using the `:join_table` 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.

Whatever the name, you must manually generate the join table with an appropriate
migration. For example, consider these associations:

```ruby
class Assembly < ApplicationRecord
  has_and_belongs_to_many :parts
end

class Part < ApplicationRecord
  has_and_belongs_to_many :assemblies
end
```

These need to be backed up by a migration to create the `assemblies_parts`
table.

```bash
$ bin/rails generate migration CreateAssembliesPartsJoinTable assemblies parts
```

You can then fill out the migration and ensure that the table is created without
a primary key.

```ruby
class CreateAssembliesPartsJoinTable < ActiveRecord::Migration[7.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
```

We pass `id: false` to `create_table` because the join table does not represent
a model. If you observe any strange behavior in a `has_and_belongs_to_many`
association like mangled model IDs, or exceptions about conflicting IDs, chances
are you forgot to set `id: false` when creating your migration.

For simplicity, you can also use the method `create_join_table`:

```ruby
class CreateAssembliesPartsJoinTable < ActiveRecord::Migration[7.2]
  def change
    create_join_table :assemblies, :parts do |t|
      t.index :assembly_id
      t.index :part_id
    end
  end
end
```

You can read more about the `create_join_table` method in the [Active Record
Migration Guides](active_record_migrations.html#creating-a-join-table)

#### Creating Join Tables for `has_many :through` Associations

The main difference in schema implementation between creating a join table for
`has_many :through` vs `has_and_belongs_to_many` is that the join table for a
`has_many :through` requires an `id`.

```ruby
class CreateAppointments < ActiveRecord::Migration[7.2]
  def change
    create_table :appointments do |t|
      t.belongs_to :physician
      t.belongs_to :patient
      t.datetime :appointment_date
      t.timestamps
    end
  end
end
```

### Controlling Association Scope

By default, associations look for objects only within the current module's
scope. This feature is particularly useful when declaring Active Record models
inside a module, as it keeps the associations scoped properly. For example:

```ruby
module MyApplication
  module Business
    class Supplier < ApplicationRecord
      has_one :account
    end

    class Account < ApplicationRecord
      belongs_to :supplier
    end
  end
end
```

In this example, both the `Supplier` and `Account` classes are defined within
the same module (`MyApplication::Business`). This organization allows you to
structure your models into folders based on their scope without needing to
explicitly specify the scope in every association:

```ruby
# app/models/my_application/business/supplier.rb
module MyApplication
  module Business
    class Supplier < ApplicationRecord
      has_one :account
    end
  end
end
```

```ruby
# app/models/my_application/business/account.rb
module MyApplication
  module Business
    class Account < ApplicationRecord
      belongs_to :supplier
    end
  end
end
```

It is important to note that while model scoping helps organize your code, it
does not change the naming convention for your database tables. For instance, if
you have a `MyApplication::Business::Supplier` model, the corresponding database
table should still follow the naming convention and be named
`my_application_business_suppliers`.

However, if the `Supplier` and `Account` models are defined in different scopes,
the associations will not work by default:

```ruby
module MyApplication
  module Business
    class Supplier < ApplicationRecord
      has_one :account
    end
  end

  module Billing
    class Account < ApplicationRecord
      belongs_to :supplier
    end
  end
end
```

To associate a model with a model in a different namespace, you must specify the
complete class name in your association declaration:

```ruby
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
```

By explicitly declaring the `class_name` option, you can create associations
across different namespaces, ensuring the correct models are linked regardless
of their module scope.

### Bi-directional Associations

In Rails, it's common for associations between models to be bi-directional,
meaning they need to be declared in both related models. Consider the following
example:

```ruby
class Author < ApplicationRecord
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :author
end
```

Active Record will attempt to automatically identify that these two models share
a bi-directional association based on the association name. This information
allows Active Record to:

* Prevent needless queries for already-loaded data:

    Active Record avoids additional database queries for already-loaded data.

    ```irb
    irb> author = Author.first
    irb> author.books.all? do |book|
    irb>   book.author.equal?(author) # No additional queries executed here
    irb> end
    => true
    ```

* Prevent inconsistent data

    Since only one copy of the `Author` object is loaded, it helps to prevent
    inconsistencies.

    ```irb
    irb> author = Author.first
    irb> book = author.books.first
    irb> author.name == book.author.name
    => true
    irb> author.name = "Changed Name"
    irb> author.name == book.author.name
    => true
    ```

* Automatic saving of associations in more cases:

    ```irb
    irb> author = Author.new
    irb> book = author.books.new
    irb> book.save!
    irb> book.persisted?
    => true
    irb> author.persisted?
    => true
    ```

* Validate the [presence](active_record_validations.html#presence) and
  [absence](active_record_validations.html#absence) of associations in more
  cases:

    ```irb
    irb> book = Book.new
    irb> book.valid?
    => false
    irb> book.errors.full_messages
    => ["Author must exist"]
    irb> author = Author.new
    irb> book = author.books.new
    irb> book.valid?
    => true
    ```

Sometimes, you might need to customize the association with options like
`:foreign_key` or `:class_name`. When you do this, Rails might not automatically
recognize the bi-directional association involving `:through` or `:foreign_key`
options.

Custom scopes on the opposite association also prevent automatic identification,
as do custom scopes on the association itself unless
[`config.active_record.automatic_scope_inversing`][] is set to true.

For example, consider the following model declarations with a custom foreign
key:

```ruby
class Author < ApplicationRecord
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :writer, class_name: 'Author', foreign_key: 'author_id'
end
```

Due to the `:foreign_key` option, Active Record will not automatically recognize
the bi-directional association, which can lead to several issues:

* Execute needless queries for the same data (in this example causing N+1
  queries):

    ```irb
    irb> author = Author.first
    irb> author.books.any? do |book|
    irb>   book.writer.equal?(author) # This executes an author query for every book
    irb> end
    => false
    ```

* Reference multiple copies of a model with inconsistent data:

    ```irb
    irb> author = Author.first
    irb> book = author.books.first
    irb> author.name == book.writer.name
    => true
    irb> author.name = "Changed Name"
    irb> author.name == book.writer.name
    => false
    ```

* Fail to autosave associations:

    ```irb
    irb> author = Author.new
    irb> book = author.books.new
    irb> book.save!
    irb> book.persisted?
    => true
    irb> author.persisted?
    => false
    ```

* Fail to validate presence or absence:

    ```irb
    irb> author = Author.new
    irb> book = author.books.new
    irb> book.valid?
    => false
    irb> book.errors.full_messages
    => ["Author must exist"]
    ```

To resolve these issues, you can explicitly declare bi-directional associations
using the `:inverse_of` option:

```ruby
class Author < ApplicationRecord
  has_many :books, inverse_of: 'writer'
end

class Book < ApplicationRecord
  belongs_to :writer, class_name: 'Author', foreign_key: 'author_id'
end
```

By including the `:inverse_of` option in the `has_many` association declaration,
Active Record will recognize the bi-directional association and behave as
described in the initial examples above.

[`config.active_record.automatic_scope_inversing`]:
    configuring.html#config-active-record-automatic-scope-inversing

Association References
----------------------

### Options

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 association
references. Such customizations can be accomplished by passing options blocks
when you create the association. For example, this association uses two such
options:

```ruby
class Book < ApplicationRecord
  belongs_to :author, touch: :books_updated_at,
    counter_cache: true
end
```

Each association supports numerous options which you can read more about in
[`Options` section of each association in the ActiveRecord Associations
API](https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html).
We'll discuss some of the common use cases below.

#### `:class_name`

If the name of the other model cannot be derived from the association name, you
can use the `:class_name` option to supply the model name. For example, if a
book belongs to an author, but the actual name of the model containing authors
is `Patron`, you'd set things up this way:

```ruby
class Book < ApplicationRecord
  belongs_to :author, class_name: "Patron"
end
```

#### `:dependent`

Controls what happens to the associated object when its owner is destroyed:

* `:destroy`, when the object is destroyed, `destroy` will be called on its
  associated objects. This method not only removes the associated records from
  the database but also ensures that any defined callbacks (like
  `before_destroy` and `after_destroy`) are executed. This is useful for
  performing custom logic during the deletion process, such as logging or
  cleaning up related data.
* `:delete`, when the object is destroyed, all its associated objects will be
  deleted directly from the database without calling their `destroy` method.
  This method performs a direct deletion and bypasses any callbacks or
  validations in the associated models, making it more efficient but potentially
  leading to data integrity issues if important cleanup tasks are skipped. Use
  `delete` when you need to remove records quickly and are confident that no
  additional actions are required for the associated records.
* `:destroy_async`: when the object is destroyed, an
  `ActiveRecord::DestroyAssociationAsyncJob` job is enqueued which will call
  destroy on its associated objects. Active Job must be set up for this to work.
  Do not use this option if the association is backed by foreign key constraints
  in your database. The foreign key constraint actions will occur inside the
  same transaction that deletes its owner.
  * `:nullify` causes the foreign key to be set to `NULL`. Polymorphic type
    column is also nullified on polymorphic associations. Callbacks are not
    executed.
  * `:restrict_with_exception` causes an `ActiveRecord::DeleteRestrictionError`
    exception to be raised if there is an associated record
  * `:restrict_with_error` causes an error to be added to the owner if there is
    an associated object

WARNING: You should not specify this option on a `belongs_to` association that
is connected with a `has_many` association on the other class. Doing so can lead
to orphaned records in your database because destroying the parent object may
attempt to destroy its children, which in turn may attempt to destroy the parent
again, causing inconsistencies.

Do not leave the `:nullify` option for associations with `NOT NULL` database
constraints. Setting `dependent` to `:destroy` is essential; otherwise, the
foreign key of the associated object may be set to `NULL`, preventing changes to
it.

NOTE: The `:dependent` option is ignored with the `:through` option. When using
`:through`, the join model must have a `belongs_to` association, and the
deletion affects only the join records, not the associated records.

When using `dependent: :destroy` on a scoped association, only the scoped
objects are destroyed. For example, in a `Post` model defined as `has_many
:comments, -> { where published: true }, dependent: :destroy`, calling destroy
on a post will only delete published comments, leaving unpublished comments
intact with a foreign key pointing to the deleted post.

You cannot use the `:dependent` option directly on a `has_and_belongs_to_many`
association. To manage deletions of join table records, handle them manually or
switch to a `has_many :through` association, which provides more flexibility and
supports the `:dependent` option.

#### `:foreign_key`

By convention, Rails assumes that the column used to hold the foreign key on
this model is the name of the association with the suffix `_id` added. The
`:foreign_key` option lets you set the name of the foreign key directly:

```ruby
class Supplier < ApplicationRecord
  has_one :account, foreign_key: "supp_id"
end
```

NOTE: Rails does not create foreign key columns for you. You need to explicitly
define them in your migrations.

#### `:primary_key`

By default, Rails uses the `id` column as the primary key for its tables. The
`:primary_key` option allows you to specify a different column as the primary
key.

For example, if the `users` table uses `guid` as the primary key instead of
`id`, and you want the `todos` table to reference `guid` as a foreign key
(`user_id`), you can configure it like this:

```ruby
class User < ApplicationRecord
  self.primary_key = 'guid' # Sets the primary key to guid instead of id
end

class Todo < ApplicationRecord
  belongs_to :user, primary_key: 'guid' # References the guid column in users table
end
```

When you execute `@user.todos.create`, the `@todo` record will have its
`user_id` value set to the `guid` value of `@user`.

`has_and_belongs_to_many` does not support the `:primary_key` option. For this
type of association, you can achieve similar functionality by using a join table
with has_many `:through` association, which gives more flexibility and supports
the `:primary_key` option. You can read more about this in the
[`has_many :through` section](#has-many-through).

#### `:touch`

If you set the `:touch` option to `true`, then the `updated_at` or `updated_on`
timestamp on the associated object will be set to the current time whenever this
object is saved or destroyed:

```ruby
class Book < ApplicationRecord
  belongs_to :author, touch: true
end

class Author < ApplicationRecord
  has_many :books
end
```

In this case, saving or destroying a book will update the timestamp on the
associated author. You can also specify a particular timestamp attribute to
update:

```ruby
class Book < ApplicationRecord
  belongs_to :author, touch: :books_updated_at
end
```

`has_and_belongs_to_many` does not support the `:touch` option. For this type of
association, you can achieve similar functionality by using a join table with
`has_many :through` association. You can read more about this in the
[`has_many :through` section](#has-many-through).

#### `:validate`

If you set the `:validate` option to `true`, then new associated objects will be
validated whenever you save this object. By default, this is `false`: new
associated objects will not be validated when this object is saved.

`has_and_belongs_to_many` does not support the `:validate` option. For this type
of association, you can achieve similar functionality by using a join table with
has_many `:through` association. You can read more about this in the
[`has_many :through` section](#has-many-through).


#### `:inverse_of`

The `:inverse_of` option specifies the name of the `belongs_to` association that
is the inverse of this association. See the [bi-directional
association](#bi-directional-associations) section for more details.

```ruby
class Supplier < ApplicationRecord
  has_one :account, inverse_of: :supplier
end

class Account < ApplicationRecord
  belongs_to :supplier, inverse_of: :account
end
```

#### `:source_type`

The `:source_type` option specifies the source association type for a `has_many
:through` association that proceeds through a [polymorphic
association](#polymorphic-associations).

```ruby
class Author < ApplicationRecord
  has_many :books
  has_many :paperbacks, through: :books, source: :format, source_type: "Paperback"
end

class Book < ApplicationRecord
  belongs_to :format, polymorphic: true
end

class Hardback < ApplicationRecord; end
class Paperback < ApplicationRecord; end
```

#### `:strict_loading`

Enforces strict loading every time an associated record is loaded through this
association.

#### `:association_foreign_key`

The `:association_foreign_key` can be found on a `has_and_belongs_to_many`
relationship. By convention, Rails assumes that the column in the join table
used to hold the foreign key pointing to the other model is the name of that
model with the suffix `_id` added. The `:association_foreign_key` option lets
you set the name of the foreign key directly For example:

```ruby
class User < ApplicationRecord
  has_and_belongs_to_many :friends,
      class_name: "User",
      foreign_key: "this_user_id",
      association_foreign_key: "other_user_id"
end
```

TIP: The `:foreign_key` and `:association_foreign_key` options are useful when
setting up a many-to-many self-join.

#### `:join_table`

The `:join_table` can be found on a `has_and_belongs_to_many` relationship. If
the default name of the join table, based on lexical ordering, is not what you
want, you can use the `:join_table` option to override the default.

### Scopes

Scopes allow you to specify common queries that can be referenced as method
calls on the association objects. This is useful for defining custom queries
that are reused in multiple places in your application. For example:

```ruby
class Parts < ApplicationRecord
  has_and_belongs_to_many :assemblies, -> { where active: true }
end
```

#### General Scopes

You can use any of the standard [querying methods](active_record_querying.html)
inside the scope block. The following ones are discussed below:


* `where`
* `includes`
* `readonly`
* `select`

##### `where`

The `where` method lets you specify the conditions that the associated object
must meet.

```ruby
class Parts < ApplicationRecord
  has_and_belongs_to_many :assemblies,
    -> { where "factory = 'Seattle'" }
end
```

You can also set conditions via a hash:

```ruby
class Parts < ApplicationRecord
  has_and_belongs_to_many :assemblies,
    -> { where factory: 'Seattle' }
end
```

If you use a hash-style `where`, then record creation via this association will
be automatically scoped using the hash. In this case, using
`@parts.assemblies.create` or `@parts.assemblies.build` will create assemblies
where the `factory` column has the value "Seattle".

##### `includes`

You can use the `includes` method to specify second-order associations that
should be eager-loaded when this association is used. For example, consider
these models:

```ruby
class Supplier < ApplicationRecord
  has_one :account
end

class Account < ApplicationRecord
  belongs_to :supplier
  belongs_to :representative
end

class Representative < ApplicationRecord
  has_many :accounts
end
```

If you frequently retrieve representatives directly from suppliers
(`@supplier.account.representative`), then you can make your code somewhat more
efficient by including representatives in the association from suppliers to
accounts:

```ruby
class Supplier < ApplicationRecord
  has_one :account, -> { includes :representative }
end

class Account < ApplicationRecord
  belongs_to :supplier
  belongs_to :representative
end

class Representative < ApplicationRecord
  has_many :accounts
end
```

NOTE: There's no need to use `includes` for immediate associations - that is, if
you have `Book belongs_to :author`, then the author is eager-loaded
automatically when it's needed.

##### `readonly`

If you use `readonly`, then the associated object will be read-only when
retrieved via the association.

```ruby
class Book < ApplicationRecord
  belongs_to :author, -> { readonly }
end
```

This is useful when you want to prevent the associated object from being
modified through the association. For example, if you have a `Book` model that
`belongs_to :author`, you can use `readonly` to prevent the author from being
modified through the book:

```ruby
@book.author = Author.first
@book.author.save! # This will raise an ActiveRecord::ReadOnlyRecord error
```

##### `select`

The `select` method lets you override the SQL `SELECT` clause used to retrieve
data about the associated object. By default, Rails retrieves all columns.

For example, if you have an `Author` model with many `Book`s, but you only want
to retrieve the `title` of each book:

```ruby
class Author < ApplicationRecord
  has_many :books, -> { select(:id, :title) } # Only select id and title columns
end

class Book < ApplicationRecord
  belongs_to :author
end
```

Now, when you access an author's books, only the `id` and `title` columns will
be retrieved from the `books` table.

TIP: If you use the `select` method on a `belongs_to` association, you should
also set the `:foreign_key` option to guarantee correct results. For example:

```ruby
class Book < ApplicationRecord
  belongs_to :author, -> { select(:id, :name) }, foreign_key: 'author_id' # Only select id and name columns
end

class Author < ApplicationRecord
  has_many :books
end
```

In this case, when you access a book's author, only the `id` and `name` columns
will be retrieved from the `authors` table.

#### Collection Scopes

`has_many` and `has_and_belongs_to_many` are associations that deal with
collections of records, so you can use additional methods like `group`, `limit`,
`order`, `select`, and `distinct` to customize the query used by the
association.

##### `group`

The `group` method supplies an attribute name to group the result set by, using
a `GROUP BY` clause in the finder SQL.

```ruby
class Parts < ApplicationRecord
  has_and_belongs_to_many :assemblies, -> { group "factory" }
end
```

##### `limit`

The `limit` method lets you restrict the total number of objects that will be
fetched through an association.

```ruby
class Parts < ApplicationRecord
  has_and_belongs_to_many :assemblies,
    -> { order("created_at DESC").limit(50) }
end
```

##### `order`

The `order` method dictates the order in which associated objects will be
received (in the syntax used by an SQL `ORDER BY` clause).

```ruby
class Author < ApplicationRecord
  has_many :books, -> { order "date_confirmed DESC" }
end
```

##### `select`

The `select` method lets you override the SQL `SELECT` clause that is used to
retrieve data about the associated objects. By default, Rails retrieves all
columns.

WARNING: If you specify your own `select`, be sure to include the primary key
and foreign key columns of the associated model. If you do not, Rails will throw
an error.

##### `distinct`

Use the `distinct` method to keep the collection free of duplicates. This is
mostly useful together with the `:through` option.

```ruby
class Person < ApplicationRecord
  has_many :readings
  has_many :articles, through: :readings
end
```

```irb
irb> person = Person.create(name: 'John')
irb> article = Article.create(name: 'a1')
irb> person.articles << article
irb> person.articles << article
irb> person.articles.to_a
=> [#<Article id: 5, name: "a1">, #<Article id: 5, name: "a1">]
irb> Reading.all.to_a
=> [#<Reading id: 12, person_id: 5, article_id: 5>, #<Reading id: 13, person_id: 5, article_id: 5>]
```

In the above case there are two readings and `person.articles` brings out both
of them even though these records are pointing to the same article.

Now let's set `distinct`:

```ruby
class Person
  has_many :readings
  has_many :articles, -> { distinct }, through: :readings
end
```

```irb
irb> person = Person.create(name: 'Honda')
irb> article = Article.create(name: 'a1')
irb> person.articles << article
irb> person.articles << article
irb> person.articles.to_a
=> [#<Article id: 7, name: "a1">]
irb> Reading.all.to_a
=> [#<Reading id: 16, person_id: 7, article_id: 7>, #<Reading id: 17, person_id: 7, article_id: 7>]
```

In the above case there are still two readings. However `person.articles` shows
only one article because the collection loads only unique records.

If you want to make sure that, upon insertion, all of the records in the
persisted association are distinct (so that you can be sure that when you
inspect the association that you will never find duplicate records), you should
add a unique index on the table itself. For example, if you have a table named
`readings` and you want to make sure the articles can only be added to a person
once, you could add the following in a migration:

```ruby
add_index :readings, [:person_id, :article_id], unique: true
```

Once you have this unique index, attempting to add the article to a person twice
will raise an `ActiveRecord::RecordNotUnique` error:

```irb
irb> person = Person.create(name: 'Honda')
irb> article = Article.create(name: 'a1')
irb> person.articles << article
irb> person.articles << article
ActiveRecord::RecordNotUnique
```

Note that checking for uniqueness using something like `include?` is subject to
race conditions. Do not attempt to use `include?` to enforce distinctness in an
association. For instance, using the article example from above, the following
code would be racy because multiple users could be attempting this at the same
time:

```ruby
person.articles << article unless person.articles.include?(article)
```

#### Using the Association Owner

You can pass the owner of the association as a single argument to the scope
block for even more control over the association scope. However, be aware that
doing this will make preloading the association impossible.

For example:

```ruby
class Supplier < ApplicationRecord
  has_one :account, ->(supplier) { where active: supplier.active? }
end
```

In this example, the `account` association of the `Supplier` model is scoped
based on the `active` status of the supplier.

By utilizing association extensions and scoping with the association owner, you
can create more dynamic and context-aware associations in your Rails
applications.

### Counter Cache

The `:counter_cache` option in Rails helps improve the efficiency of finding the
number of associated objects. Consider the following models:

```ruby
class Book < ApplicationRecord
  belongs_to :author
end

class Author < ApplicationRecord
  has_many :books
end
```

By default, querying `@auth books.size` results in a database call to perform a
`COUNT(*)` query. To optimize this, you can add a counter cache to the
_belonging_ model (in this case, `Book`). This way, Rails can return the count
directly from the cache without querying the database.

```ruby
class Book < ApplicationRecord
  belongs_to :author, counter_cache: true
end

class Author < ApplicationRecord
  has_many :books
end
```

With this declaration, Rails will keep the cache value up to date, and then
return that value in response to the `size` method, avoiding the database call.

Although the `:counter_cache` option is specified on the model with the
`belongs_to` declaration, the actual column must be added to the _associated_
(in this case `has_many`) model. In this example, you need to add a
`books_count` column to the `Author` model:

```ruby
class AddBooksCountToAuthors < ActiveRecord::Migration[6.0]
  def change
    add_column :authors, :books_count, :integer, default: 0, null: false
  end
end
```

You can specify a custom column name in the `counter_cache` declaration instead
of using the default `books_count`. For example, to use `count_of_books`:

```ruby
class Book < ApplicationRecord
  belongs_to :author, counter_cache: :count_of_books
end

class Author < ApplicationRecord
  has_many :books
end
```

NOTE: You only need to specify the `:counter_cache` option on the `belongs_to`
side of the association.

Using counter caches on existing large tables can be troublesome. To avoid
locking the table for too long, the column values must be backfilled separately
from the column addition. This backfill must also happen before using
`:counter_cache`; otherwise, methods like `size`, `any?`, etc., which rely on
counter caches, may return incorrect results.

To backfill values safely while keeping counter cache columns updated with child
record creation/removal and ensuring methods always get results from the
database (avoiding potentially incorrect counter cache values), use
`counter_cache: { active: false }`. This setting ensures that methods always
fetch results from the database, avoiding incorrect values from an uninitialized
counter cache. If you need to specify a custom column name, use `counter_cache:
{ active: false, column: :my_custom_counter }`.

If for some reason you change the value of an owner model's primary key, and do
not also update the foreign keys of the counted models, then the counter cache
may have stale data. In other words, any orphaned models will still count
towards the counter. To fix a stale counter cache, use
[`reset_counters`](https://api.rubyonrails.org/classes/ActiveRecord/CounterCache/ClassMethods.html#method-i-reset_counters).

### Callbacks

[Normal callbacks](active_record_callbacks.html) hook into the life cycle of
Active Record objects, allowing you to work with those objects at various
points. For example, you can use a `:before_save` callback to cause something to
happen just before an object is saved.

Association callbacks are similar to normal callbacks, but they are triggered by
events in the life cycle of a collection associated with an Active Record
object. There are four available association callbacks:

* `before_add`
* `after_add`
* `before_remove`
* `after_remove`

You define association callbacks by adding options to the association
declaration. For example:

```ruby
class Author < ApplicationRecord
  has_many :books, before_add: :check_credit_limit

  def check_credit_limit(book)
    throw(:abort) if limit_reached?
  end
end
```

In this example, the `Author` model has a `has_many` association with `books`.
The `before_add` callback `check_credit_limit` is triggered before a book is
added to the collection. If the `limit_reached?` method returns `true`, the book
is not added to the collection.

By using these association callbacks, you can customize the behavior of your
associations, ensuring that specific actions are taken at key points in the life
cycle of your collections.

Read more about association callbacks in the [Active Record Callbacks
Guide](active_record_callbacks.html#association-callbacks)

### Extensions

Rails provides the ability to extend the functionality of association proxy
objects, which manage associations, by adding new finders, creators, or other
methods through anonymous modules. This feature allows you to customize
associations to meet the specific needs of your application.

You can extend a `has_many` association with custom methods directly within the
model definition. For example:

```ruby
class Author < ApplicationRecord
  has_many :books do
    def find_by_book_prefix(book_number)
      find_by(category_id: book_number[0..2])
    end
  end
end
```

In this example, the `find_by_book_prefix` method is added to the `books`
association of the `Author` model. This custom method allows you to find `books`
based on a specific prefix of the `book_number`.

If you have an extension that should be shared by multiple associations, you can
use a named extension module. For example:

```ruby
module FindRecentExtension
  def find_recent
    where("created_at > ?", 5.days.ago)
  end
end

class Author < ApplicationRecord
  has_many :books, -> { extending FindRecentExtension }
end

class Supplier < ApplicationRecord
  has_many :deliveries, -> { extending FindRecentExtension }
end
```

In this case, the `FindRecentExtension` module is used to add a `find_recent`
method to both the `books` association in the `Author` model and the
`deliveries` association in the `Supplier` model. This method retrieves records
created within the last five days.

Extensions can interact with the internals of the association proxy using the
`proxy_association` accessor. The `proxy_association` provides three important
attributes:

* `proxy_association.owner` returns the object that the association is a part
  of.
* `proxy_association.reflection` returns the reflection object that describes
  the association.
* `proxy_association.target` returns the associated object for `belongs_to` or
  `has_one`, or the collection of associated objects for `has_many` or
  `has_and_belongs_to_many`.

These attributes allow extensions to access and manipulate the association
proxy's internal state and behavior.

Here's an advanced example demonstrating how to use these attributes in an
extension:

```ruby
module AdvancedExtension
  def find_and_log(query)
    results = where(query)
    proxy_association.owner.logger.info("Querying #{proxy_association.reflection.name} with #{query}")
    results
  end
end

class Author < ApplicationRecord
  has_many :books, -> { extending AdvancedExtension }
end
```

In this example, the `find_and_log` method performs a query on the association
and logs the query details using the owner's logger. The method accesses the
owner's logger via `proxy_association.owner` and the association's name via
`proxy_association.reflection`.name.