aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/html/association_basics.html
blob: 012a1a0156e5a3979fcf4f6c430a669274d68fcf (plain) (blame)
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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>A Guide to Active Record Associations</title>
	<!--[if lt IE 8]>
	<script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
	<![endif]-->
	<link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
	<link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
	<link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
	<style type="text/css">
		div#container {
	max-width: 900px;
	padding-bottom: 3em;
}

div#content {
	margin-left: 200px;
}

div#container.notoc {
	max-width: 600px;
}

.notoc div#content {
	margin-left: 0;
}

pre {
	line-height: 1.4em;
}

#content p tt {
	background: #eeeeee;
	border: solid 1px #cccccc;
	padding: 3px;
}

dt {
	font-weight: bold;
}

#content dt tt {
	font-size: 10pt;
}

dd {
	margin-left: 3em;
}

#content dt tt, #content pre tt {
	background: none;
	padding: 0;
	border: 0;
}

#content .olist ol {
	margin-left: 2em;
}

#header {
	position: relative;
	max-width: 840px;
	margin-left: auto;
	margin-right: auto;
}

#header.notoc {
	max-width: 580px;
}

#logo {
	position: absolute;
	left: 10px;
	top: 10px;
	width: 110px;
	height: 140px;
}

div#header h1#site_title {
	background: url('images/ruby_on_rails_by_mike_rundle2.gif') top left no-repeat;
	position: absolute;
	width: 392px;
	height: 55px;
	left: 145px;
	top: 20px;
	margin: 0;
	padding: 0;
}

#site_title span {
	display: none;
}

#site_title_tagline {
	display: none;
}

ul#navMain {
	position: absolute;
	margin: 0;
	padding: 0;
	top: 97px;
	left: 145px;
}

.left-floaty, .right-floaty {
	padding: 15px;
}

.admonitionblock,
.tableblock {
	margin-left: 1em;
	margin-right: 1em;
	margin-top: 0.25em;
	margin-bottom: 1em;
}

.admonitionblock .icon {
	padding-right: 8px;
}

.admonitionblock .content {
	border: solid 1px #ffda78;
	background: #fffebd;
	padding: 10px;
	padding-top: 8px;
	padding-bottom: 8px;
}

.admonitionblock .title {
	font-size: 140%;
	margin-bottom: 0.5em;
}

.tableblock table {
	border: solid 1px #aaaaff;
	background: #f0f0ff;
}

.tableblock th {
	background: #e0e0e0;
}

.tableblock th,
.tableblock td {
	padding: 3px;
	padding-left: 5px;
	padding-right: 5px;
}

.sidebarblock {
	margin-top: 0.25em;
	margin: 1em;
	border: solid 1px #ccccbb;
	padding: 8px;
	background: #ffffe0;
}

.sidebarblock .sidebar-title {
	font-size: 140%;
	font-weight: 600;
	margin-bottom: 0.3em;
}

.sidebarblock .sidebar-content > .para:last-child > p {
	margin-bottom: 0;
}

.sidebarblock .sidebar-title a {
	text-decoration: none;
}

.sidebarblock .sidebar-title a:hover {
	text-decoration: underline;
}

	</style>
</head>
<body>
	<div id="header" >
		<div id="logo">
			<a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
		</div>
		
		<h1 id="site_title"><span>Ruby on Rails</span></h1>
		<h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>

		<ul id="navMain">
			<li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
			<li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
		</ul>
	</div>

	<div id="container">
		
		<div id="sidebar">
			<h2>Chapters</h2>
			<ol>
					<li>
					<a href="#_why_associations">Why Associations?</a>
					</li>
					<li>
					<a href="#_the_types_of_associations">The Types of Associations</a>
						<ul>
						
							<li><a href="#_the_tt_belongs_to_tt_association">The <tt>belongs_to</tt> Association</a></li>
						
							<li><a href="#_the_tt_has_one_tt_association">The <tt>has_one</tt> Association</a></li>
						
							<li><a href="#_the_tt_has_many_tt_association">The <tt>has_many</tt> Association</a></li>
						
							<li><a href="#_the_tt_has_many_through_tt_association">The <tt>has_many :through</tt> Association</a></li>
						
							<li><a href="#_the_tt_has_one_through_tt_association">The <tt>has_one :through</tt> Association</a></li>
						
							<li><a href="#_the_tt_has_and_belongs_to_many_tt_association">The <tt>has_and_belongs_to_many</tt> Association</a></li>
						
							<li><a href="#_choosing_between_tt_belongs_to_tt_and_tt_has_one_tt">Choosing Between <tt>belongs_to</tt> and <tt>has_one</tt></a></li>
						
							<li><a href="#_choosing_between_tt_has_many_through_tt_and_tt_has_and_belongs_to_many_tt">Choosing Between <tt>has_many :through</tt> and <tt>has_and_belongs_to_many</tt></a></li>
						
							<li><a href="#_polymorphic_associations">Polymorphic Associations</a></li>
						
							<li><a href="#_self_joins">Self Joins</a></li>
						
						</ul>
					</li>
					<li>
					<a href="#_tips_tricks_and_warnings">Tips, Tricks, and Warnings</a>
						<ul>
						
							<li><a href="#_controlling_caching">Controlling Caching</a></li>
						
							<li><a href="#_avoiding_name_collisions">Avoiding Name Collisions</a></li>
						
							<li><a href="#_updating_the_schema">Updating the Schema</a></li>
						
							<li><a href="#_controlling_association_scope">Controlling Association Scope</a></li>
						
						</ul>
					</li>
					<li>
					<a href="#_detailed_association_reference">Detailed Association Reference</a>
						<ul>
						
							<li><a href="#_the_tt_belongs_to_tt_association_2">The <tt>belongs_to</tt> Association</a></li>
						
							<li><a href="#_the_has_one_association">The has_one Association</a></li>
						
							<li><a href="#_the_has_many_association">The has_many Association</a></li>
						
							<li><a href="#_the_tt_has_and_belongs_to_many_tt_association_2">The <tt>has_and_belongs_to_many</tt> Association</a></li>
						
							<li><a href="#_association_callbacks">Association Callbacks</a></li>
						
							<li><a href="#_association_extensions">Association Extensions</a></li>
						
						</ul>
					</li>
					<li>
					<a href="#_changelog">Changelog</a>
					</li>
			</ol>
		</div>
		
		<div id="content">
				<h1>A Guide to Active Record Associations</h1>
			<div id="preamble">
<div class="sectionbody">
<div class="para"><p>This guide covers the association features of Active Record. By referring to this guide, you will be able to:</p></div>
<div class="ilist"><ul>
<li>
<p>
Declare associations between Active Record models
</p>
</li>
<li>
<p>
Understand the various types of Active Record associations
</p>
</li>
<li>
<p>
Use the methods added to your models by creating associations
</p>
</li>
</ul></div>
</div>
</div>
<h2 id="_why_associations">1. Why Associations?</h2>
<div class="sectionbody">
<div class="para"><p>Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order</span> <span style="color: #990000">=</span> Order<span style="color: #990000">.</span>create<span style="color: #990000">(:</span>order_date <span style="color: #990000">=&gt;</span> Time<span style="color: #990000">.</span>now<span style="color: #990000">,</span> <span style="color: #990000">:</span>customer_id <span style="color: #990000">=&gt;</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>id<span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="para"><p>Or consider deleting a customer, and ensuring that all of its orders get deleted as well:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@orders</span> <span style="color: #990000">=</span> Order<span style="color: #990000">.</span>find_by_customer_id<span style="color: #990000">(</span><span style="color: #009900">@customer</span><span style="color: #990000">.</span>id<span style="color: #990000">)</span>
<span style="color: #009900">@orders</span><span style="color: #990000">.</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>order<span style="color: #990000">|</span>
  order<span style="color: #990000">.</span>destroy
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="color: #009900">@customer</span><span style="color: #990000">.</span>destroy
</tt></pre></div></div>
<div class="para"><p>With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>With this change, creating a new order for a particular customer is easier:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders<span style="color: #990000">.</span>create<span style="color: #990000">(:</span>order_date <span style="color: #990000">=&gt;</span> Time<span style="color: #990000">.</span>now<span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="para"><p>Deleting a customer and all of its orders is <em>much</em> easier:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@customer</span><span style="color: #990000">.</span>destroy
</tt></pre></div></div>
<div class="para"><p>To learn more about the different types of associations, read the next section of this Guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.</p></div>
</div>
<h2 id="_the_types_of_associations">2. The Types of Associations</h2>
<div class="sectionbody">
<div class="para"><p>In Rails, an <em>association</em> is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model <tt>belongs_to</tt> another, you instruct Rails to maintain Primary Key-Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>belongs_to</tt>
</p>
</li>
<li>
<p>
<tt>has_one</tt>
</p>
</li>
<li>
<p>
<tt>has_many</tt>
</p>
</li>
<li>
<p>
<tt>has_many :through</tt>
</p>
</li>
<li>
<p>
<tt>has_one :through</tt>
</p>
</li>
<li>
<p>
<tt>has_and_belongs_to_many</tt>
</p>
</li>
</ul></div>
<div class="para"><p>In the remainder of this guide, you'll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.</p></div>
<h3 id="_the_tt_belongs_to_tt_association">2.1. The <tt>belongs_to</tt> Association</h3>
<div class="para"><p>A <tt>belongs_to</tt> association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p><span class="image">
<img src="images/belongs_to.png" alt="belongs_to Association Diagram" title="belongs_to Association Diagram" />
</span></p></div>
<h3 id="_the_tt_has_one_tt_association">2.2. The <tt>has_one</tt> Association</h3>
<div class="para"><p>A <tt>has_one</tt> association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p><span class="image">
<img src="images/has_one.png" alt="has_one Association Diagram" title="has_one Association Diagram" />
</span></p></div>
<h3 id="_the_tt_has_many_tt_association">2.3. The <tt>has_many</tt> Association</h3>
<div class="para"><p>A <tt>has_many</tt> association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a <tt>belongs_to</tt> association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">The name of the other model is pluralized when declaring a <tt>has_many</tt> association.</td>
</tr></table>
</div>
<div class="para"><p><span class="image">
<img src="images/has_many.png" alt="has_many Association Diagram" title="has_many Association Diagram" />
</span></p></div>
<h3 id="_the_tt_has_many_through_tt_association">2.4. The <tt>has_many :through</tt> Association</h3>
<div class="para"><p>A <tt>has_many :through</tt> association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding <em>through</em> a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Physician <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>appointments
  has_many <span style="color: #990000">:</span>patients<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>appointments
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Appointment <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>physician
  belongs_to <span style="color: #990000">:</span>patient
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Patient <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>appointments
  has_many <span style="color: #990000">:</span>physicians<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>appointments
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p><span class="image">
<img src="images/has_many_through.png" alt="has_many :through Association Diagram" title="has_many :through Association Diagram" />
</span></p></div>
<div class="para"><p>The <tt>has_many :through</tt> association is also useful for setting up "shortcuts" through nested :<tt>has_many</tt> associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Document <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>sections
  has_many <span style="color: #990000">:</span>paragraphs<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>sections
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Section <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>document
  has_many <span style="color: #990000">:</span>paragraphs
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Paragraph <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>section
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h3 id="_the_tt_has_one_through_tt_association">2.5. The <tt>has_one :through</tt> Association</h3>
<div class="para"><p>A <tt>has_one :through</tt> association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding <em>through</em> a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account
  has_one <span style="color: #990000">:</span>account_history<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>account
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>supplier
  has_one <span style="color: #990000">:</span>account_history
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AccountHistory <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>account
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p><span class="image">
<img src="images/has_one_through.png" alt="has_one :through Association Diagram" title="has_one :through Association Diagram" />
</span></p></div>
<h3 id="_the_tt_has_and_belongs_to_many_tt_association">2.6. The <tt>has_and_belongs_to_many</tt> Association</h3>
<div class="para"><p>A <tt>has_and_belongs_to_many</tt> association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Assembly <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>parts
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Part <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p><span class="image">
<img src="images/habtm.png" alt="has_and_belongs_to_many Association Diagram" title="has_and_belongs_to_many Association Diagram" />
</span></p></div>
<h3 id="_choosing_between_tt_belongs_to_tt_and_tt_has_one_tt">2.7. Choosing Between <tt>belongs_to</tt> and <tt>has_one</tt></h3>
<div class="para"><p>If you want to set up a 1-1 relationship between two models, you'll need to add <tt>belongs_to</tt> to one, and <tt>has_one</tt> to the other. How do you know which is which?</p></div>
<div class="para"><p>The distinction is in where you place the foreign key (it goes on the table for the class declaring the <tt>belongs_to</tt> association), but you should give some thought to the actual meaning of the data as well. The <tt>has_one</tt> relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>supplier
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The corresponding migration might look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreateSuppliers <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
    create_table <span style="color: #990000">:</span>suppliers <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
      t<span style="color: #990000">.</span>string  <span style="color: #990000">:</span>name
      t<span style="color: #990000">.</span>timestamps
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

    create_table <span style="color: #990000">:</span>accounts <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
      t<span style="color: #990000">.</span>integer <span style="color: #990000">:</span>supplier_id
      t<span style="color: #990000">.</span>string  <span style="color: #990000">:</span>account_number
      t<span style="color: #990000">.</span>timestamps
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
    drop_table <span style="color: #990000">:</span>accounts
    drop_table <span style="color: #990000">:</span>suppliers
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">Using <tt>t.integer :supplier_id</tt> makes the foreign key naming obvious and implicit. In current versions of Rails, you can abstract away this implementation detail by using <tt>t.references :supplier</tt> instead.</td>
</tr></table>
</div>
<h3 id="_choosing_between_tt_has_many_through_tt_and_tt_has_and_belongs_to_many_tt">2.8. Choosing Between <tt>has_many :through</tt> and <tt>has_and_belongs_to_many</tt></h3>
<div class="para"><p>Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use <tt>has_and_belongs_to_many</tt>, which allows you to make the association directly:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Assembly <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>parts
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Part <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The second way to declare a many-to-many relationship is to use <tt>has_many :through</tt>. This makes the association indirectly, through a join model:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Assembly <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>manifests
  has_many <span style="color: #990000">:</span>parts<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>manifests
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Manifest <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>assembly
  belongs_to <span style="color: #990000">:</span>part
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Part <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>manifests
  has_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>manifests
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The simplest rule of thumb is that you should set up a <tt>has_many :through</tt> relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a <tt>has_and_belongs_to_many</tt> relationship (though you'll need to remember to create the joining table).</p></div>
<div class="para"><p>You should use <tt>has_many :through</tt> if you need validations, callbacks, or extra attributes on the join model.</p></div>
<h3 id="_polymorphic_associations">2.9. Polymorphic Associations</h3>
<div class="para"><p>A slightly more advanced twist on associations is the <em>polymorphic association</em>. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Picture <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>imageable<span style="color: #990000">,</span> <span style="color: #990000">:</span>polymorphic <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Employee <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>pictures<span style="color: #990000">,</span> <span style="color: #990000">:</span>as <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>imageable
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Product <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>pictures<span style="color: #990000">,</span> <span style="color: #990000">:</span>as <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>imageable
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>You can think of a polymorphic <tt>belongs_to</tt> declaration as setting up an interface that any other model can use. From an instance of the <tt>Employee</tt> model, you can retrieve a collection of pictures: <tt>@employee.pictures</tt>. Similarly, you can retrieve <tt>@product.pictures</tt>. If you have an instance of the <tt>Picture</tt> model, you can get to its parent via <tt>@picture.imageable</tt>. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreatePictures <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
    create_table <span style="color: #990000">:</span>pictures <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
      t<span style="color: #990000">.</span>string  <span style="color: #990000">:</span>name
      t<span style="color: #990000">.</span>integer <span style="color: #990000">:</span>imageable_id
      t<span style="color: #990000">.</span>string  <span style="color: #990000">:</span>imageable_type
      t<span style="color: #990000">.</span>timestamps
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
    drop_table <span style="color: #990000">:</span>pictures
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>This migration can be simplified by using the <tt>t.references</tt> form:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreatePictures <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
    create_table <span style="color: #990000">:</span>pictures <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
      t<span style="color: #990000">.</span>string  <span style="color: #990000">:</span>name
      t<span style="color: #990000">.</span>references <span style="color: #990000">:</span>imageable<span style="color: #990000">,</span> <span style="color: #990000">:</span>polymorphic <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
      t<span style="color: #990000">.</span>timestamps
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
    drop_table <span style="color: #990000">:</span>pictures
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p><span class="image">
<img src="images/polymorphic.png" alt="Polymorphic Association Diagram" title="Polymorphic Association Diagram" />
</span></p></div>
<h3 id="_self_joins">2.10. Self Joins</h3>
<div class="para"><p>In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as manager and subordinates. This situation can be modeled with self-joining associations:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Employee <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>subordinates<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"User"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"manager_id"</span>
  belongs_to <span style="color: #990000">:</span>manager<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"User"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>With this setup, you can retrieve <tt>@employee.subordinates</tt> and <tt>@employee.managers</tt>.</p></div>
</div>
<h2 id="_tips_tricks_and_warnings">3. Tips, Tricks, and Warnings</h2>
<div class="sectionbody">
<div class="para"><p>Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:</p></div>
<div class="ilist"><ul>
<li>
<p>
Controlling caching
</p>
</li>
<li>
<p>
Avoiding name collisions
</p>
</li>
<li>
<p>
Updating the schema
</p>
</li>
<li>
<p>
Controlling association scope
</p>
</li>
</ul></div>
<h3 id="_controlling_caching">3.1. Controlling Caching</h3>
<div class="para"><p>All of the association methods are built around caching that keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>customer<span style="color: #990000">.</span>orders                 <span style="font-style: italic"><span style="color: #9A1900"># retrieves orders from the database</span></span>
customer<span style="color: #990000">.</span>orders<span style="color: #990000">.</span>size            <span style="font-style: italic"><span style="color: #9A1900"># uses the cached copy of orders</span></span>
customer<span style="color: #990000">.</span>orders<span style="color: #990000">.</span>empty?          <span style="font-style: italic"><span style="color: #9A1900"># uses the cached copy of orders</span></span>
</tt></pre></div></div>
<div class="para"><p>But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass <tt>true</tt> to the association call:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>customer<span style="color: #990000">.</span>orders                 <span style="font-style: italic"><span style="color: #9A1900"># retrieves orders from the database</span></span>
customer<span style="color: #990000">.</span>orders<span style="color: #990000">.</span>size            <span style="font-style: italic"><span style="color: #9A1900"># uses the cached copy of orders</span></span>
customer<span style="color: #990000">.</span>orders<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">true</span></span><span style="color: #990000">).</span>empty?    <span style="font-style: italic"><span style="color: #9A1900"># discards the cached copy of orders and goes back to the database</span></span>
</tt></pre></div></div>
<h3 id="_avoiding_name_collisions">3.2. Avoiding Name Collisions</h3>
<div class="para"><p>You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of <tt>ActiveRecord::Base</tt>. The association method would override the base method and break things. For instance, <tt>attributes</tt> or <tt>connection</tt> are bad names for associations.</p></div>
<h3 id="_updating_the_schema">3.3. Updating the Schema</h3>
<div class="para"><p>Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things. First, you need to create foreign keys as appropriate:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>This declaration needs to be backed up by the proper foreign key declaration on the orders table:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreateOrders <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
    create_table <span style="color: #990000">:</span>orders <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
      t<span style="color: #990000">.</span>order_date   <span style="color: #990000">:</span>datetime
      t<span style="color: #990000">.</span>order_number <span style="color: #990000">:</span>string
      t<span style="color: #990000">.</span>customer_id  <span style="color: #990000">:</span>integer
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
    drop_table <span style="color: #990000">:</span>orders
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>If you create an association some time after you build the underlying model, you need to remember to create an <tt>add_column</tt> migration to provide the necessary foreign key.</p></div>
<div class="para"><p>Second, if you create a <tt>has_and_belongs_to_many</tt> association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the <tt>:join_table</tt> option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">The precedence between model names is calculated using the <tt>&lt;</tt> operator for <tt>String</tt>. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers".</td>
</tr></table>
</div>
<div class="para"><p>Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Assembly <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>parts
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Part <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>These need to be backed up by a migration to create the <tt>assemblies_parts</tt> table. This table should be created without a primary key:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreateAssemblyPartJoinTable <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
    create_table <span style="color: #990000">:</span>assemblies_parts<span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
      t<span style="color: #990000">.</span>integer <span style="color: #990000">:</span>assembly_id
      t<span style="color: #990000">.</span>integer <span style="color: #990000">:</span>part_id
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
    drop_table <span style="color: #990000">:</span>assemblies_parts
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h3 id="_controlling_association_scope">3.4. Controlling Association Scope</h3>
<div class="para"><p>By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> MyApplication
  <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Business
    <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
       has_one <span style="color: #990000">:</span>account
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

    <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
       belongs_to <span style="color: #990000">:</span>supplier
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>This will work fine, because both the <tt>Supplier</tt> and the <tt>Account</tt> class are defined within the same scope. But this will not work, because <tt>Supplier</tt> and <tt>Account</tt> are defined in different scopes:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> MyApplication
  <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Business
    <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
       has_one <span style="color: #990000">:</span>account
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Billing
    <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
       belongs_to <span style="color: #990000">:</span>supplier
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>To associate a model with a model in a different scope, you must specify the complete class name in your association declaration:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> MyApplication
  <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Business
    <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
       has_one <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"MyApplication::Billing::Account"</span>
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Billing
    <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
       belongs_to <span style="color: #990000">:</span>supplier<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"MyApplication::Business::Supplier"</span>
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
<h2 id="_detailed_association_reference">4. Detailed Association Reference</h2>
<div class="sectionbody">
<div class="para"><p>The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.</p></div>
<h3 id="_the_tt_belongs_to_tt_association_2">4.1. The <tt>belongs_to</tt> Association</h3>
<div class="para"><p>The <tt>belongs_to</tt> association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use <tt>has_one</tt> instead.</p></div>
<h4 id="_methods_added_by_tt_belongs_to_tt">4.1.1. Methods Added by <tt>belongs_to</tt></h4>
<div class="para"><p>When you declare a <tt>belongs_to</tt> assocation, the declaring class automatically gains five methods related to the association:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt><em>association</em>(force_reload = false)</tt>
</p>
</li>
<li>
<p>
<tt><em>association</em>=(associate)</tt>
</p>
</li>
<li>
<p>
<tt><em>association</em>.nil?</tt>
</p>
</li>
<li>
<p>
<tt>build<em>_association</em>(attributes = {})</tt>
</p>
</li>
<li>
<p>
<tt>create<em>_association</em>(attributes = {})</tt>
</p>
</li>
</ul></div>
<div class="para"><p>In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to <tt>belongs_to</tt>. For example, given the declaration:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Each instance of the order model will have these methods:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>customer
customer<span style="color: #990000">=</span>
customer<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
build_customer
create_customer
</tt></pre></div></div>
<h5 id="_tt_em_association_em_force_reload_false_tt"><tt><em>association</em>(force_reload = false)</tt></h5>
<div class="para"><p>The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns <tt>nil</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@customer</span> <span style="color: #990000">=</span> <span style="color: #009900">@order</span><span style="color: #990000">.</span>customer
</tt></pre></div></div>
<div class="para"><p>If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass <tt>true</tt> as the <tt>force_reload</tt> argument.</p></div>
<h5 id="_tt_em_association_em_associate_tt"><tt><em>association</em>=(associate)</tt></h5>
<div class="para"><p>The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order</span><span style="color: #990000">.</span>customer <span style="color: #990000">=</span> <span style="color: #009900">@customer</span>
</tt></pre></div></div>
<h5 id="_tt_em_association_em_nil_tt"><tt><em>association</em>.nil?</tt></h5>
<div class="para"><p>The <tt><em>association</em>.nil?</tt> method returns <tt>true</tt> if there is no associated object.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #009900">@order</span><span style="color: #990000">.</span>customer<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
  <span style="color: #009900">@msg</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"No customer found for this order"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_build_em_association_em_attributes_tt"><tt>build<em>_association</em>(attributes = {})</tt></h5>
<div class="para"><p>The <tt>build<em>_association</em></tt> 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.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@customer</span> <span style="color: #990000">=</span> <span style="color: #009900">@order</span><span style="color: #990000">.</span>build_customer<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>customer_number <span style="color: #990000">=&gt;</span> <span style="color: #993399">123</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>customer_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"John Doe"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<h5 id="_tt_create_em_association_em_attributes_tt"><tt>create<em>_association</em>(attributes = {})</tt></h5>
<div class="para"><p>The <tt>create<em>_association</em></tt> 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. In addition, the associated object _will_ be saved (assuming that it passes any validations).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@customer</span> <span style="color: #990000">=</span> <span style="color: #009900">@order</span><span style="color: #990000">.</span>create_customer<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>customer_number <span style="color: #990000">=&gt;</span> <span style="color: #993399">123</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>customer_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"John Doe"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<h4 id="_options_for_tt_belongs_to_tt">4.1.2. Options for <tt>belongs_to</tt></h4>
<div class="para"><p>In many situations, you can use the default behavior of <tt>belongs_to</tt> without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a <tt>belongs_to</tt> association. For example, an association with several options might look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer<span style="color: #990000">,</span> <span style="color: #990000">:</span>counter_cache <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span><span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"active = 1"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The <tt>belongs_to</tt> association supports these options:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>:class_name</tt>
</p>
</li>
<li>
<p>
<tt>:conditions</tt>
</p>
</li>
<li>
<p>
<tt>:counter_cache</tt>
</p>
</li>
<li>
<p>
<tt>:dependent</tt>
</p>
</li>
<li>
<p>
<tt>:foreign_key</tt>
</p>
</li>
<li>
<p>
<tt>:include</tt>
</p>
</li>
<li>
<p>
<tt>:polymorphic</tt>
</p>
</li>
<li>
<p>
<tt>:readonly</tt>
</p>
</li>
<li>
<p>
<tt>:select</tt>
</p>
</li>
<li>
<p>
<tt>:validate</tt>
</p>
</li>
</ul></div>
<h5 id="_tt_class_name_tt"><tt>:class_name</tt></h5>
<div class="para"><p>If the name of the other model cannot be derived from the association name, you can use the <tt>:class_name</tt> option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is <tt>Patron</tt>, you'd set things up this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Patron"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_conditions_tt"><tt>:conditions</tt></h5>
<div class="para"><p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL <tt>WHERE</tt> clause).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"active = 1"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_counter_cache_tt"><tt>:counter_cache</tt></h5>
<div class="para"><p>The <tt>:counter_cache</tt> option can be used to make finding the number of belonging objects more efficient. Consider these models:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>With these declarations, asking for the value of <tt>@customer.orders.size</tt> requires making a call to the database to perform a <tt>COUNT(*)</tt> query. To avoid this call, you can add a counter cache to the <em>belonging</em> model:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer<span style="color: #990000">,</span> <span style="color: #990000">:</span>counter_cache <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>With this declaration, Rails will keep the cache value up to date, and then return that value in response to the <tt>.size</tt> method.</p></div>
<div class="para"><p>Although the <tt>:counter_cache</tt> option is specified on the model that includes the <tt>belongs_to</tt> declaration, the actual column must be added to the <em>associated</em> model. In the case above, you would need to add a column named <tt>orders_count</tt> to the <tt>Customer</tt> model. You can override the default column name if you need to:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer<span style="color: #990000">,</span> <span style="color: #990000">:</span>counter_cache <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>count_of_orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Counter cache columns are added to the containing model's list of read-only attributes through <tt>attr_readonly</tt>.</p></div>
<h5 id="_tt_dependent_tt"><tt>:dependent</tt></h5>
<div class="para"><p>If you set the <tt>:dependent</tt> option to <tt>:destroy</tt>, then deleting this object will call the destroy method on the associated object to delete that object. If you set the <tt>:dependent</tt> option to <tt>:delete</tt>, then deleting this object will delete the associated object <em>without</em> calling its <tt>destroy</tt> method.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">You should not specify this option on a <tt>belongs_to</tt> association that is connected with a <tt>has_many</tt> association on the other class. Doing so can lead to orphaned records in your database.</td>
</tr></table>
</div>
<h5 id="_tt_foreign_key_tt"><tt>:foreign_key</tt></h5>
<div class="para"><p>By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Patron"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"patron_id"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.</td>
</tr></table>
</div>
<h5 id="_tt_include_tt"><tt>:include</tt></h5>
<div class="para"><p>You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LineItem <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>order
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
  has_many <span style="color: #990000">:</span>line_items
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>If you frequently retrieve customers directly from line items (<tt>@line_item.order.customer</tt>), then you can make your code somewhat more efficient by including customers in the association from line items to orders:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LineItem <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>order<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>customer
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
  has_many <span style="color: #990000">:</span>line_items
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">There's no need to use <tt>:include</tt> for immediate associations - that is, if you have <tt>Order belongs_to :customer</tt>, then the customer is eager-loaded automatically when it's needed.</td>
</tr></table>
</div>
<h5 id="_tt_polymorphic_tt"><tt>:polymorphic</tt></h5>
<div class="para"><p>Passing <tt>true</tt> to the <tt>:polymorphic</tt> option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.</p></div>
<h5 id="_tt_readonly_tt"><tt>:readonly</tt></h5>
<div class="para"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated object will be read-only when retrieved via the association.</p></div>
<h5 id="_tt_select_tt"><tt>:select</tt></h5>
<div class="para"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.</p></div>
<h5 id="_tt_validate_tt"><tt>:validate</tt></h5>
<div class="para"><p>If you set the <tt>:validate</tt> option to <tt>true</tt>, then associated objects will be validated whenever you save this object. By default, this is <tt>false</tt>: associated objects will not be validated when this object is saved.</p></div>
<h4 id="_when_are_objects_saved">4.1.3. When are Objects Saved?</h4>
<div class="para"><p>Assigning an object to a <tt>belongs_to</tt> association does <em>not</em> automatically save the object. It does not save the associated object either.</p></div>
<h3 id="_the_has_one_association">4.2. The has_one Association</h3>
<div class="para"><p>The <tt>has_one</tt> 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 <tt>belongs_to</tt> instead.</p></div>
<h4 id="_methods_added_by_tt_has_one_tt">4.2.1. Methods Added by <tt>has_one</tt></h4>
<div class="para"><p>When you declare a <tt>has_one</tt> association, the declaring class automatically gains five methods related to the association:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt><em>association</em>(force_reload = false)</tt>
</p>
</li>
<li>
<p>
<tt><em>association</em>=(associate)</tt>
</p>
</li>
<li>
<p>
<tt><em>association</em>.nil?</tt>
</p>
</li>
<li>
<p>
<tt>build<em>_association</em>(attributes = {})</tt>
</p>
</li>
<li>
<p>
<tt>create<em>_association</em>(attributes = {})</tt>
</p>
</li>
</ul></div>
<div class="para"><p>In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to <tt>has_one</tt>. For example, given the declaration:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Each instance of the <tt>Supplier</tt> model will have these methods:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>account
account<span style="color: #990000">=</span>
account<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
build_account
create_account
</tt></pre></div></div>
<h5 id="_tt_em_association_em_force_reload_false_tt_2"><tt><em>association</em>(force_reload = false)</tt></h5>
<div class="para"><p>The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns <tt>nil</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@account</span> <span style="color: #990000">=</span> <span style="color: #009900">@supplier</span><span style="color: #990000">.</span>account
</tt></pre></div></div>
<div class="para"><p>If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass <tt>true</tt> as the <tt>force_reload</tt> argument.</p></div>
<h5 id="_tt_em_association_em_associate_tt_2"><tt><em>association</em>=(associate)</tt></h5>
<div class="para"><p>The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@suppler</span><span style="color: #990000">.</span>account <span style="color: #990000">=</span> <span style="color: #009900">@account</span>
</tt></pre></div></div>
<h5 id="_tt_em_association_em_nil_tt_2"><tt><em>association</em>.nil?</tt></h5>
<div class="para"><p>The <tt><em>association</em>.nil?</tt> method returns <tt>true</tt> if there is no associated object.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #009900">@supplier</span><span style="color: #990000">.</span>account<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
  <span style="color: #009900">@msg</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"No account found for this supplier"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_build_em_association_em_attributes_tt_2"><tt>build<em>_association</em>(attributes = {})</tt></h5>
<div class="para"><p>The <tt>build<em>_association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@account</span> <span style="color: #990000">=</span> <span style="color: #009900">@supplier</span><span style="color: #990000">.</span>build_account<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>terms <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Net 30"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<h5 id="_tt_create_em_association_em_attributes_tt_2"><tt>create<em>_association</em>(attributes = {})</tt></h5>
<div class="para"><p>The <tt>create<em>_association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@account</span> <span style="color: #990000">=</span> <span style="color: #009900">@supplier</span><span style="color: #990000">.</span>create_account<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>terms <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Net 30"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<h4 id="_options_for_tt_has_one_tt">4.2.2. Options for <tt>has_one</tt></h4>
<div class="para"><p>In many situations, you can use the default behavior of <tt>has_one</tt> without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a <tt>has_one</tt> association. For example, an association with several options might look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Billing"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>dependent <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>nullify
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The <tt>has_one</tt> association supports these options:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>:as</tt>
</p>
</li>
<li>
<p>
<tt>:class_name</tt>
</p>
</li>
<li>
<p>
<tt>:conditions</tt>
</p>
</li>
<li>
<p>
<tt>:dependent</tt>
</p>
</li>
<li>
<p>
<tt>:foreign_key</tt>
</p>
</li>
<li>
<p>
<tt>:include</tt>
</p>
</li>
<li>
<p>
<tt>:order</tt>
</p>
</li>
<li>
<p>
<tt>:primary_key</tt>
</p>
</li>
<li>
<p>
<tt>:readonly</tt>
</p>
</li>
<li>
<p>
<tt>:select</tt>
</p>
</li>
<li>
<p>
<tt>:source</tt>
</p>
</li>
<li>
<p>
<tt>:source_type</tt>
</p>
</li>
<li>
<p>
<tt>:through</tt>
</p>
</li>
<li>
<p>
<tt>:validate</tt>
</p>
</li>
</ul></div>
<h5 id="_tt_as_tt"><tt>:as</tt></h5>
<div class="para"><p>Setting the <tt>:as</tt> option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.</p></div>
<h5 id="_tt_class_name_tt_2"><tt>:class_name</tt></h5>
<div class="para"><p>If the name of the other model cannot be derived from the association name, you can use the <tt>:class_name</tt> option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, you'd set things up this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Billing"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_conditions_tt_2"><tt>:conditions</tt></h5>
<div class="para"><p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL <tt>WHERE</tt> clause).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"confirmed = 1"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_dependent_tt_2"><tt>:dependent</tt></h5>
<div class="para"><p>If you set the <tt>:dependent</tt> option to <tt>:destroy</tt>, then deleting this object will call the destroy method on the associated object to delete that object. If you set the <tt>:dependent</tt> option to <tt>:delete</tt>, then deleting this object will delete the associated object <em>without</em> calling its <tt>destroy</tt> method. If you set the <tt>:dependent</tt> option to <tt>:nullify</tt>, then deleting this object will set the foreign key in the association object to <tt>NULL</tt>.</p></div>
<h5 id="_tt_foreign_key_tt_2"><tt>:foreign_key</tt></h5>
<div class="para"><p>By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"supp_id"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.</td>
</tr></table>
</div>
<h5 id="_tt_include_tt_2"><tt>:include</tt></h5>
<div class="para"><p>You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>supplier
  belongs_to <span style="color: #990000">:</span>representative
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Representative <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>accounts
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>If you frequently retrieve representatives directly from suppliers (<tt>@supplier.account.representative</tt>), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>representative
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>supplier
  belongs_to <span style="color: #990000">:</span>representative
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Representative <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>accounts
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_order_tt"><tt>:order</tt></h5>
<div class="para"><p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by a SQL <tt>ORDER BY</tt> clause). Because a <tt>has_one</tt> association will only retrieve a single associated object, this option should not be needed.</p></div>
<h5 id="_tt_primary_key_tt"><tt>:primary_key</tt></h5>
<div class="para"><p>By convention, Rails guesses that the column used to hold the primary key of this model is <tt>id</tt>. You can override this and explicitly specify the primary key with the <tt>:primary_key</tt> option.</p></div>
<h5 id="_tt_readonly_tt_2"><tt>:readonly</tt></h5>
<div class="para"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated object will be read-only when retrieved via the association.</p></div>
<h5 id="_tt_select_tt_2"><tt>:select</tt></h5>
<div class="para"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.</p></div>
<h5 id="_tt_source_tt"><tt>:source</tt></h5>
<div class="para"><p>The <tt>:source</tt> option specifies the source association name for a <tt>has_one :through</tt> association.</p></div>
<h5 id="_tt_source_type_tt"><tt>:source_type</tt></h5>
<div class="para"><p>The <tt>:source_type</tt> option specifies the source association type for a <tt>has_one :through</tt> association that proceeds through a polymorphic association.</p></div>
<h5 id="_tt_through_tt"><tt>:through</tt></h5>
<div class="para"><p>The <tt>:through</tt> option specifies a join model through which to perform the query. <tt>has_one :through</tt> associations are discussed in detail later in this guide.</p></div>
<h5 id="_tt_validate_tt_2"><tt>:validate</tt></h5>
<div class="para"><p>If you set the <tt>:validate</tt> option to <tt>true</tt>, then associated objects will be validated whenever you save this object. By default, this is <tt>false</tt>: associated objects will not be validated when this object is saved.</p></div>
<h4 id="_when_are_objects_saved_2">4.2.3. When are Objects Saved?</h4>
<div class="para"><p>When you assign an object to a <tt>has_one</tt> association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.</p></div>
<div class="para"><p>If either of these saves fails due to validation errors, then the assignment statement returns <tt>false</tt> and the assignment itself is cancelled.</p></div>
<div class="para"><p>If the parent object (the one declaring the <tt>has_one</tt> association) is unsaved (that is, <tt>new_record?</tt> returns <tt>true</tt>) then the child objects are not saved.</p></div>
<div class="para"><p>If you want to assign an object to a <tt>has_one</tt> association without saving the object, use the <tt>association.build</tt> method.</p></div>
<h3 id="_the_has_many_association">4.3. The has_many Association</h3>
<div class="para"><p>The <tt>has_many</tt> 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.</p></div>
<h4 id="_methods_added">4.3.1. Methods Added</h4>
<div class="para"><p>When you declare a <tt>has_many</tt> association, the declaring class automatically gains 13 methods related to the association:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt><em>collection</em>(force_reload = false)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>&lt;&lt;(object, &#8230;)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.delete(object, &#8230;)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>=objects</tt>
</p>
</li>
<li>
<p>
<tt><em>collection_singular</em>_ids</tt>
</p>
</li>
<li>
<p>
<tt><em>collection_singular</em>_ids=ids</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.clear</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.empty?</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.size</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.find(&#8230;)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.exist?(&#8230;)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.build(attributes = {}, &#8230;)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.create(attributes = {})</tt>
</p>
</li>
</ul></div>
<div class="para"><p>In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to <tt>has_many</tt>, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Each instance of the customer model will have these methods:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>orders<span style="color: #990000">(</span>force_reload <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span><span style="color: #990000">)</span>
orders<span style="color: #990000">&lt;&lt;(</span>object<span style="color: #990000">,</span> <span style="color: #990000">...)</span>
orders<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>object<span style="color: #990000">,</span> <span style="color: #990000">...)</span>
orders<span style="color: #990000">=</span>objects
order_ids
order_ids<span style="color: #990000">=</span>ids
orders<span style="color: #990000">.</span>clear
orders<span style="color: #990000">.</span>empty?
orders<span style="color: #990000">.</span>size
orders<span style="color: #990000">.</span>find<span style="color: #990000">(...)</span>
orders<span style="color: #990000">.</span>exist?<span style="color: #990000">(...)</span>
orders<span style="color: #990000">.</span>build<span style="color: #990000">(</span>attributes <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">,</span> <span style="color: #990000">...)</span>
orders<span style="color: #990000">.</span>create<span style="color: #990000">(</span>attributes <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_force_reload_false_tt"><tt><em>collection</em>(force_reload = false)</tt></h5>
<div class="para"><p>The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@orders</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_lt_lt_object_8230_tt"><tt><em>collection</em>&lt;&lt;(object, &#8230;)</tt></h5>
<div class="para"><p>The <tt><em>collection</em>&lt;&lt;</tt> method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders <span style="color: #990000">&lt;&lt;</span> <span style="color: #009900">@order1</span>
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_delete_object_8230_tt"><tt><em>collection</em>.delete(object, &#8230;)</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by setting their foreign keys to <tt>NULL</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders<span style="color: #990000">.</span>delete<span style="color: #990000">(</span><span style="color: #009900">@order1</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">Objects will be in addition destroyed if they're associated with <tt>:dependent &#8658; :destroy</tt>, and deleted if they're associated with <tt>:dependent &#8658; :delete_all</tt>.</td>
</tr></table>
</div>
<h5 id="_tt_em_collection_em_objects_tt"><tt><em>collection</em>=objects</tt></h5>
<div class="para"><p>The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.</p></div>
<h5 id="_tt_em_collection_singular_em_ids_tt"><tt><em>collection_singular</em>_ids</tt></h5>
<div class="para"><p>The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order_ids</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>order_ids
</tt></pre></div></div>
<h5 id="_tt_em_collection_singular_em_ids_ids_tt"><tt><em>_collection_singular</em>_ids=ids</tt></h5>
<div class="para"><p>The <tt><em>_collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.</p></div>
<h5 id="_tt_em_collection_em_clear_tt"><tt><em>collection</em>.clear</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.clear</tt> method removes every object from the collection. This destroys the associated objects if they are associated with <tt>:dependent &#8658; :destroy</tt>, deletes them directly from the database if <tt>:dependent &#8658; :delete_all</tt>, and otherwise sets their foreign keys to <tt>NULL</tt>.</p></div>
<h5 id="_tt_em_collection_em_empty_tt"><tt><em>collection</em>.empty?</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.empty?</tt> method returns <tt>true</tt> if the collection does not contain any associated objects.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #FF0000">&lt;% if @customer.orders.empty? %&gt;</span>
  No Orders Found
<span style="color: #FF0000">&lt;% end %&gt;</span>
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_size_tt"><tt><em>collection</em>.size</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order_count</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders<span style="color: #990000">.</span>size
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_find_8230_tt"><tt><em>collection</em>.find(&#8230;)</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as <tt>ActiveRecord::Base.find</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@open_orders</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders<span style="color: #990000">.</span>find<span style="color: #990000">(:</span>all<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"open = 1"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_exist_8230_tt"><tt><em>collection</em>.exist?(&#8230;)</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.exist?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as <tt>ActiveRecord::Base.exists?</tt>.</p></div>
<h5 id="_tt_em_collection_em_build_attributes_8230_tt"><tt><em>collection</em>.build(attributes = {}, &#8230;)</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.build</tt> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will <em>not</em> yet be saved.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders<span style="color: #990000">.</span>build<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>order_date <span style="color: #990000">=&gt;</span> Time<span style="color: #990000">.</span>now<span style="color: #990000">,</span> <span style="color: #990000">:</span>order_number <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"A12345"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_create_attributes_tt"><tt><em>collection</em>.create(attributes = {})</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object <em>will</em> be saved (assuming that it passes any validations).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders<span style="color: #990000">.</span>create<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>order_date <span style="color: #990000">=&gt;</span> Time<span style="color: #990000">.</span>now<span style="color: #990000">,</span> <span style="color: #990000">:</span>order_number <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"A12345"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<h4 id="_options_for_has_many">4.3.2. Options for has_many</h4>
<div class="para"><p>In many situations, you can use the default behavior for <tt>has_many</tt> without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a <tt>has_many</tt> association. For example, an association with several options might look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>dependent <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>delete_all<span style="color: #990000">,</span> <span style="color: #990000">:</span>validate <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The <tt>has_many</tt> association supports these options:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>:as</tt>
</p>
</li>
<li>
<p>
<tt>:class_name</tt>
</p>
</li>
<li>
<p>
<tt>:conditions</tt>
</p>
</li>
<li>
<p>
<tt>:counter_sql</tt>
</p>
</li>
<li>
<p>
<tt>:dependent</tt>
</p>
</li>
<li>
<p>
<tt>:extend</tt>
</p>
</li>
<li>
<p>
<tt>:finder_sql</tt>
</p>
</li>
<li>
<p>
<tt>:foreign_key</tt>
</p>
</li>
<li>
<p>
<tt>:group</tt>
</p>
</li>
<li>
<p>
<tt>:include</tt>
</p>
</li>
<li>
<p>
<tt>:limit</tt>
</p>
</li>
<li>
<p>
<tt>:offset</tt>
</p>
</li>
<li>
<p>
<tt>:order</tt>
</p>
</li>
<li>
<p>
<tt>:primary_key</tt>
</p>
</li>
<li>
<p>
<tt>:readonly</tt>
</p>
</li>
<li>
<p>
<tt>:select</tt>
</p>
</li>
<li>
<p>
<tt>:source</tt>
</p>
</li>
<li>
<p>
<tt>:source_type</tt>
</p>
</li>
<li>
<p>
<tt>:through</tt>
</p>
</li>
<li>
<p>
<tt>:uniq</tt>
</p>
</li>
<li>
<p>
<tt>:validate</tt>
</p>
</li>
</ul></div>
<h5 id="_tt_as_tt_2"><tt>:as</tt></h5>
<div class="para"><p>Setting the <tt>:as</tt> option indicates that this is a polymorphic association, as discussed earlier in this guide.</p></div>
<h5 id="_tt_class_name_tt_3"><tt>:class_name</tt></h5>
<div class="para"><p>If the name of the other model cannot be derived from the association name, you can use the <tt>:class_name</tt> option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is <tt>Transaction</tt>, you'd set things up this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Transaction"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_conditions_tt_3"><tt>:conditions</tt></h5>
<div class="para"><p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL <tt>WHERE</tt> clause).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>confirmed_orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Order"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"confirmed = 1"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>You can also set conditions via a hash:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>confirmed_orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Order"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>confirmed <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>If you use a hash-style <tt>:conditions</tt> option, then record creation via this association will be automatically scoped using the hash. In this case, using <tt>@customer.confirmed_orders.create</tt> or <tt>@customer.confirmed_orders.build</tt> will create orders where the confirmed column has the value <tt>true</tt>.</p></div>
<h5 id="_tt_counter_sql_tt"><tt>:counter_sql</tt></h5>
<div class="para"><p>Normally Rails automatically generates the proper SQL to count the association members. With the <tt>:counter_sql</tt> option, you can specify a complete SQL statement to count them yourself.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">If you specify <tt>:finder_sql</tt> but not <tt>:counter_sql</tt>, then the counter SQL will be generated by substituting <tt>SELECT COUNT(*) FROM</tt> for the <tt>SELECT &#8230; FROM</tt> clause of your <tt>:finder_sql</tt> statement.</td>
</tr></table>
</div>
<h5 id="_tt_dependent_tt_3"><tt>:dependent</tt></h5>
<div class="para"><p>If you set the <tt>:dependent</tt> option to <tt>:destroy</tt>, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the <tt>:dependent</tt> option to <tt>:delete_all</tt>, then deleting this object will delete the associated objects <em>without</em> calling their <tt>destroy</tt> method. If you set the <tt>:dependent</tt> option to <tt>:nullify</tt>, then deleting this object will set the foreign key in the associated objects to <tt>NULL</tt>.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">This option is ignored when you use the <tt>:through</tt> option on the association.</td>
</tr></table>
</div>
<h5 id="_tt_extend_tt"><tt>:extend</tt></h5>
<div class="para"><p>The <tt>:extend</tt> option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.</p></div>
<h5 id="_tt_finder_sql_tt"><tt>:finder_sql</tt></h5>
<div class="para"><p>Normally Rails automatically generates the proper SQL to fetch the association members. With the <tt>:finder_sql</tt> option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.</p></div>
<h5 id="_tt_foreign_key_tt_3"><tt>:foreign_key</tt></h5>
<div class="para"><p>By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"cust_id"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.</td>
</tr></table>
</div>
<h5 id="_tt_group_tt"><tt>:group</tt></h5>
<div class="para"><p>The <tt>:group</tt> option supplies an attribute name to group the result set by, using a <tt>GROUP BY</tt> clause in the finder SQL.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>line_items<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>group <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"orders.id"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_include_tt_3"><tt>:include</tt></h5>
<div class="para"><p>You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
  has_many <span style="color: #990000">:</span>line_items
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LineItem <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>order
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>If you frequently retrieve line items directly from customers (<tt>@customer.orders.line_items</tt>), then you can make your code somewhat more efficient by including line items in the association from customers to orders:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>line_items
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
  has_many <span style="color: #990000">:</span>line_items
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LineItem <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>order
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_limit_tt"><tt>:limit</tt></h5>
<div class="para"><p>The <tt>:limit</tt> option lets you restrict the total number of objects that will be fetched through an association.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>recent_orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Order"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>order <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"order_date DESC"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>limit <span style="color: #990000">=&gt;</span> <span style="color: #993399">100</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_offset_tt"><tt>:offset</tt></h5>
<div class="para"><p>The <tt>:offset</tt> option lets you specify the starting offset for fetching objects via an association. For example, if you set <tt>:offset &#8658; 11</tt>, it will skip the first 10 records.</p></div>
<h5 id="_tt_order_tt_2"><tt>:order</tt></h5>
<div class="para"><p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by a SQL <tt>ORDER BY</tt> clause).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>order <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"date_confirmed DESC"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_primary_key_tt_2"><tt>:primary_key</tt></h5>
<div class="para"><p>By convention, Rails guesses that the column used to hold the primary key of this model is <tt>id</tt>. You can override this and explicitly specify the primary key with the <tt>:primary_key</tt> option.</p></div>
<h5 id="_tt_readonly_tt_3"><tt>:readonly</tt></h5>
<div class="para"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated objects will be read-only when retrieved via the association.</p></div>
<h5 id="_tt_select_tt_3"><tt>:select</tt></h5>
<div class="para"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">If you specify your own <tt>:select</tt>, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.</td>
</tr></table>
</div>
<h5 id="_tt_source_tt_2"><tt>:source</tt></h5>
<div class="para"><p>The <tt>:source</tt> option specifies the source association name for a <tt>has_many :through</tt> association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.</p></div>
<h5 id="_tt_source_type_tt_2"><tt>:source_type</tt></h5>
<div class="para"><p>The <tt>:source_type</tt> option specifies the source association type for a <tt>has_many :through</tt> association that proceeds through a polymorphic association.</p></div>
<h5 id="_tt_through_tt_2"><tt>:through</tt></h5>
<div class="para"><p>The <tt>:through</tt> option specifies a join model through which to perform the query. <tt>has_many :through</tt> associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.</p></div>
<h5 id="_tt_uniq_tt"><tt>:uniq</tt></h5>
<div class="para"><p>Specify the <tt>:uniq &#8658; true</tt> option to remove duplicates from the collection. This is most useful in conjunction with the <tt>:through</tt> option.</p></div>
<h5 id="_tt_validate_tt_3"><tt>:validate</tt></h5>
<div class="para"><p>If you set the <tt>:validate</tt> option to <tt>false</tt>, then associated objects will not be validated whenever you save this object. By default, this is <tt>true</tt>: associated objects will be validated when this object is saved.</p></div>
<h4 id="_when_are_objects_saved_3">4.3.3. When are Objects Saved?</h4>
<div class="para"><p>When you assign an object to a <tt>has_many</tt> 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.</p></div>
<div class="para"><p>If any of these saves fails due to validation errors, then the assignment statement returns <tt>false</tt> and the assignment itself is cancelled.</p></div>
<div class="para"><p>If the parent object (the one declaring the <tt>has_many</tt> association) is unsaved (that is, <tt>new_record?</tt> returns <tt>true</tt>) 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.</p></div>
<div class="para"><p>If you want to assign an object to a <tt>has_many</tt> association without saving the object, use the <tt><em>collection</em>.build</tt> method.</p></div>
<h3 id="_the_tt_has_and_belongs_to_many_tt_association_2">4.4. The <tt>has_and_belongs_to_many</tt> Association</h3>
<div class="para"><p>The <tt>has_and_belongs_to_many</tt> 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.</p></div>
<h4 id="_methods_added_2">4.4.1. Methods Added</h4>
<div class="para"><p>When you declare a <tt>has_and_belongs_to_many</tt> association, the declaring class automatically gains 13 methods related to the association:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt><em>collection</em>(force_reload = false)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>&lt;&lt;(object, &#8230;)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.delete(object, &#8230;)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>=objects</tt>
</p>
</li>
<li>
<p>
<tt><em>collection_singular</em>_ids</tt>
</p>
</li>
<li>
<p>
<tt><em>collection_singular</em>_ids=ids</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.clear</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.empty?</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.size</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.find(&#8230;)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.exist?(&#8230;)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.build(attributes = {})</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.create(attributes = {})</tt>
</p>
</li>
</ul></div>
<div class="para"><p>In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to <tt>has_many</tt>, and <tt><em>collection</em>_singular</tt> is replaced with the singularized version of that symbol.. For example, given the declaration:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Part <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Each instance of the part model will have these methods:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>assemblies<span style="color: #990000">(</span>force_reload <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span><span style="color: #990000">)</span>
assemblies<span style="color: #990000">&lt;&lt;(</span>object<span style="color: #990000">,</span> <span style="color: #990000">...)</span>
assemblies<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>object<span style="color: #990000">,</span> <span style="color: #990000">...)</span>
assemblies<span style="color: #990000">=</span>objects
assembly_ids
assembly_ids<span style="color: #990000">=</span>ids
assemblies<span style="color: #990000">.</span>clear
assemblies<span style="color: #990000">.</span>empty?
assemblies<span style="color: #990000">.</span>size
assemblies<span style="color: #990000">.</span>find<span style="color: #990000">(...)</span>
assemblies<span style="color: #990000">.</span>exist?<span style="color: #990000">(...)</span>
assemblies<span style="color: #990000">.</span>build<span style="color: #990000">(</span>attributes <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">,</span> <span style="color: #990000">...)</span>
assemblies<span style="color: #990000">.</span>create<span style="color: #990000">(</span>attributes <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<h5 id="_additional_column_methods">Additional Column Methods</h5>
<div class="para"><p>If the join table for a <tt>has_and_belongs_to_many</tt> 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.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">The use of extra attributes on the join table in a <tt>has_and_belongs_to_many</tt> 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 <tt>has_many :through</tt> association instead of <tt>has_and_belongs_to_many</tt>.</td>
</tr></table>
</div>
<h5 id="_tt_em_collection_em_force_reload_false_tt_2"><tt><em>collection</em>(force_reload = false)</tt></h5>
<div class="para"><p>The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@assemblies</span> <span style="color: #990000">=</span> <span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_lt_lt_object_8230_tt_2"><tt><em>collection</em>&lt;&lt;(object, &#8230;)</tt></h5>
<div class="para"><p>The <tt><em>collection</em>&lt;&lt;</tt> method adds one or more objects to the collection by creating records in the join table.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies <span style="color: #990000">&lt;&lt;</span> <span style="color: #009900">@assembly1</span>
</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>.</td>
</tr></table>
</div>
<h5 id="_tt_em_collection_em_delete_object_8230_tt_2"><tt><em>collection</em>.delete(object, &#8230;)</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies<span style="color: #990000">.</span>delete<span style="color: #990000">(</span><span style="color: #009900">@assembly1</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_objects_tt_2"><tt><em>collection</em>=objects</tt></h5>
<div class="para"><p>The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.</p></div>
<h5 id="_tt_em_collection_singular_em_ids_tt_2"><tt><em>collection_singular</em>_ids</tt></h5>
<div class="para"><p>#   Returns an array of the associated objects' ids</p></div>
<div class="para"><p>The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@assembly_ids</span> <span style="color: #990000">=</span> <span style="color: #009900">@part</span><span style="color: #990000">.</span>assembly_ids
</tt></pre></div></div>
<h5 id="_tt_em_collection_singular_em_ids_ids_tt_2"><tt><em>collection_singular</em>_ids=ids</tt></h5>
<div class="para"><p>The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.</p></div>
<h5 id="_tt_em_collection_em_clear_tt_2"><tt><em>collection</em>.clear</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining tableassociation. This does not destroy the associated objects.</p></div>
<h5 id="_tt_em_collection_em_empty_tt_2"><tt><em>collection</em>.empty?</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.empty?</tt> method returns <tt>true</tt> if the collection does not contain any associated objects.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #FF0000">&lt;% if @part.assemblies.empty? %&gt;</span>
  This part is <span style="font-weight: bold"><span style="color: #0000FF">not</span></span> used <span style="font-weight: bold"><span style="color: #0000FF">in</span></span> any assemblies
<span style="color: #FF0000">&lt;% end %&gt;</span>
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_size_tt_2"><tt><em>collection</em>.size</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@assembly_count</span> <span style="color: #990000">=</span> <span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies<span style="color: #990000">.</span>size
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_find_8230_tt_2"><tt><em>collection</em>.find(&#8230;)</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as <tt>ActiveRecord::Base.find</tt>. It also adds the additional condition that the object must be in the collection.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@new_assemblies</span> <span style="color: #990000">=</span> <span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies<span style="color: #990000">.</span>find<span style="color: #990000">(:</span>all<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span><span style="color: #FF0000">"created_at &gt; ?"</span><span style="color: #990000">,</span> <span style="color: #993399">2</span><span style="color: #990000">.</span>days<span style="color: #990000">.</span>ago<span style="color: #990000">])</span>
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_exist_8230_tt_2"><tt><em>collection</em>.exist?(&#8230;)</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.exist?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as <tt>ActiveRecord::Base.exists?</tt>.</p></div>
<h5 id="_tt_em_collection_em_build_attributes_tt"><tt><em>collection</em>.build(attributes = {})</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.build</tt> 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 <em>not</em> yet be saved.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@assembly</span> <span style="color: #990000">=</span> <span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies<span style="color: #990000">.</span>build<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>assembly_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Transmission housing"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<h5 id="_tt_em_collection_em_create_attributes_tt_2"><tt><em>collection</em>.create(attributes = {})</tt></h5>
<div class="para"><p>The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This objects will be instantiated from the passed attributes, the link through the join table will be created, and the associated object <em>will</em> be saved (assuming that it passes any validations).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@assembly</span> <span style="color: #990000">=</span> <span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies<span style="color: #990000">.</span>create<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>assembly_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Transmission housing"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<h4 id="_options_for_has_and_belongs_to_many">4.4.2. Options for has_and_belongs_to_many</h4>
<div class="para"><p>In many situations, you can use the default behavior for <tt>has_and_belongs_to_many</tt> without any customization. But you can alter that behavior in a number of ways. This section cover the options that you can pass when you create a <tt>has_and_belongs_to_many</tt> association. For example, an association with several options might look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>uniq <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span><span style="color: #990000">,</span> <span style="color: #990000">:</span>read_only <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The <tt>has_and_belongs_to_many</tt> association supports these options:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>:association_foreign_key</tt>
</p>
</li>
<li>
<p>
<tt>:class_name</tt>
</p>
</li>
<li>
<p>
<tt>:conditions</tt>
</p>
</li>
<li>
<p>
<tt>:counter_sql</tt>
</p>
</li>
<li>
<p>
<tt>:delete_sql</tt>
</p>
</li>
<li>
<p>
<tt>:extend</tt>
</p>
</li>
<li>
<p>
<tt>:finder_sql</tt>
</p>
</li>
<li>
<p>
<tt>:foreign_key</tt>
</p>
</li>
<li>
<p>
<tt>:group</tt>
</p>
</li>
<li>
<p>
<tt>:include</tt>
</p>
</li>
<li>
<p>
<tt>:insert_sql</tt>
</p>
</li>
<li>
<p>
<tt>:join_table</tt>
</p>
</li>
<li>
<p>
<tt>:limit</tt>
</p>
</li>
<li>
<p>
<tt>:offset</tt>
</p>
</li>
<li>
<p>
<tt>:order</tt>
</p>
</li>
<li>
<p>
<tt>:readonly</tt>
</p>
</li>
<li>
<p>
<tt>:select</tt>
</p>
</li>
<li>
<p>
<tt>:uniq</tt>
</p>
</li>
<li>
<p>
<tt>:validate</tt>
</p>
</li>
</ul></div>
<h5 id="_tt_association_foreign_key_tt"><tt>:association_foreign_key</tt></h5>
<div class="para"><p>By convention, Rails guesses 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 <tt>_id</tt> added. The <tt>:association_foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">The <tt>:foreign_key</tt> and <tt>:association_foreign_key</tt> options are useful when setting up a many-to-many self-join. For example:</td>
</tr></table>
</div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> User <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>friends<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"User"</span><span style="color: #990000">,</span>
    <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"this_user_id"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>association_foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"other_user_id"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_class_name_tt_4"><tt>:class_name</tt></h5>
<div class="para"><p>If the name of the other model cannot be derived from the association name, you can use the <tt>:class_name</tt> option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is <tt>Gadget</tt>, you'd set things up this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Gadget"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_conditions_tt_4"><tt>:conditions</tt></h5>
<div class="para"><p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL <tt>WHERE</tt> clause).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"factory = 'Seattle'"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>You can also set conditions via a hash:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>factory <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'Seattle'</span> <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>If you use a hash-style <tt>:conditions</tt> option, then record creation via this association will be automatically scoped using the hash. In this case, using <tt>@parts.assemblies.create</tt> or <tt>@parts.assemblies.build</tt> will create orders where the factory column has the value "Seattle".</p></div>
<h5 id="_tt_counter_sql_tt_2"><tt>:counter_sql</tt></h5>
<div class="para"><p>Normally Rails automatically generates the proper SQL to count the association members. With the <tt>:counter_sql</tt> option, you can specify a complete SQL statement to count them yourself.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">If you specify <tt>:finder_sql</tt> but not <tt>:counter_sql</tt>, then the counter SQL will be generated by substituting <tt>SELECT COUNT(*) FROM</tt> for the <tt>SELECT &#8230; FROM</tt> clause of your <tt>:finder_sql</tt> statement.</td>
</tr></table>
</div>
<h5 id="_tt_delete_sql_tt"><tt>:delete_sql</tt></h5>
<div class="para"><p>Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the <tt>:delete_sql</tt> option, you can specify a complete SQL statement to delete them yourself.</p></div>
<h5 id="_tt_extend_tt_2"><tt>:extend</tt></h5>
<div class="para"><p>The <tt>:extend</tt> option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.</p></div>
<h5 id="_tt_finder_sql_tt_2"><tt>:finder_sql</tt></h5>
<div class="para"><p>Normally Rails automatically generates the proper SQL to fetch the association members. With the <tt>:finder_sql</tt> option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.</p></div>
<h5 id="_tt_foreign_key_tt_4"><tt>:foreign_key</tt></h5>
<div class="para"><p>By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> User <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>friends<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"User"</span><span style="color: #990000">,</span>
    <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"this_user_id"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>association_foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"other_user_id"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_group_tt_2"><tt>:group</tt></h5>
<div class="para"><p>The <tt>:group</tt> option supplies an attribute name to group the result set by, using a <tt>GROUP BY</tt> clause in the finder SQL.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>group <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"factory"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_include_tt_4"><tt>:include</tt></h5>
<div class="para"><p>You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.</p></div>
<h5 id="_tt_insert_sql_tt"><tt>:insert_sql</tt></h5>
<div class="para"><p>Normally Rails automatically generates the proper SQL to create links between the associated classes. With the <tt>:insert_sql</tt> option, you can specify a complete SQL statement to insert them yourself.</p></div>
<h5 id="_tt_join_table_tt"><tt>:join_table</tt></h5>
<div class="para"><p>If the default name of the join table, based on lexical ordering, is not what you want, you can use the <tt>:join_table</tt> option to override the default.</p></div>
<h5 id="_tt_limit_tt_2"><tt>:limit</tt></h5>
<div class="para"><p>The <tt>:limit</tt> option lets you restrict the total number of objects that will be fetched through an association.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>order <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"created_at DESC"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>limit <span style="color: #990000">=&gt;</span> <span style="color: #993399">50</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_offset_tt_2"><tt>:offset</tt></h5>
<div class="para"><p>The <tt>:offset</tt> option lets you specify the starting offset for fetching objects via an association. For example, if you set <tt>:offset &#8658; 11</tt>, it will skip the first 10 records.</p></div>
<h5 id="_tt_order_tt_3"><tt>:order</tt></h5>
<div class="para"><p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by a SQL <tt>ORDER BY</tt> clause).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>order <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"assembly_name ASC"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_readonly_tt_4"><tt>:readonly</tt></h5>
<div class="para"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated objects will be read-only when retrieved via the association.</p></div>
<h5 id="_tt_select_tt_4"><tt>:select</tt></h5>
<div class="para"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.</p></div>
<h5 id="_tt_uniq_tt_2"><tt>:uniq</tt></h5>
<div class="para"><p>Specify the <tt>:uniq &#8658; true</tt> option to remove duplicates from the collection.</p></div>
<h5 id="_tt_validate_tt_4"><tt>:validate</tt></h5>
<div class="para"><p>If you set the <tt>:validate</tt> option to <tt>false</tt>, then associated objects will not be validated whenever you save this object. By default, this is <tt>true</tt>: associated objects will be validated when this object is saved.</p></div>
<h4 id="_when_are_objects_saved_4">4.4.3. When are Objects Saved?</h4>
<div class="para"><p>When you assign an object to a <tt>has_and_belongs_to_many</tt> 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.</p></div>
<div class="para"><p>If any of these saves fails due to validation errors, then the assignment statement returns <tt>false</tt> and the assignment itself is cancelled.</p></div>
<div class="para"><p>If the parent object (the one declaring the <tt>has_and_belongs_to_many</tt> association) is unsaved (that is, <tt>new_record?</tt> returns <tt>true</tt>) 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.</p></div>
<div class="para"><p>If you want to assign an object to a <tt>has_and_belongs_to_many</tt> association without saving the object, use the <tt><em>collection</em>.build</tt> method.</p></div>
<h3 id="_association_callbacks">4.5. Association Callbacks</h3>
<div class="para"><p>Normal callbacks hook into the lifecycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a <tt>:before_save</tt> callback to cause something to happen just before an object is saved.</p></div>
<div class="para"><p>Association callbacks are similar to normal callbacks, but they are triggered by events in the lifecycle of a collection. There are four available association callbacks:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>before_add</tt>
</p>
</li>
<li>
<p>
<tt>after_add</tt>
</p>
</li>
<li>
<p>
<tt>before_remove</tt>
</p>
</li>
<li>
<p>
<tt>after_remove</tt>
</p>
</li>
</ul></div>
<div class="para"><p>You define association callbacks by adding options to the association declaration. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>before_add <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>check_credit_limit

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> check_credit_limit<span style="color: #990000">(</span>order<span style="color: #990000">)</span>
    <span style="color: #990000">...</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Rails passes the object being added or removed to the callback.</p></div>
<div class="para"><p>You can stack callbacks on a single event by passing them as an array:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>before_add <span style="color: #990000">=&gt;</span> <span style="color: #990000">[:</span>check_credit_limit<span style="color: #990000">,</span> <span style="color: #990000">:</span>calculate_shipping_charges<span style="color: #990000">]</span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> check_credit_limit<span style="color: #990000">(</span>order<span style="color: #990000">)</span>
    <span style="color: #990000">...</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> calculate_shipping_charges<span style="color: #990000">(</span>order<span style="color: #990000">)</span>
    <span style="color: #990000">...</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>If a <tt>before_add</tt> callback throws an exception, the object does not get added to the collection. Similarly, if a <tt>before_remove</tt> callback throws an exception, the object does not get removed from the collection.</p></div>
<h3 id="_association_extensions">4.6. Association Extensions</h3>
<div class="para"><p>You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
    <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> find_by_order_prefix<span style="color: #990000">(</span>order_number<span style="color: #990000">)</span>
      find_by_region_id<span style="color: #990000">(</span>order_number<span style="color: #990000">[</span><span style="color: #993399">0</span><span style="color: #990000">..</span><span style="color: #993399">2</span><span style="color: #990000">])</span>
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>If you have an extension that should be shared by many associations, you can use a named extension module. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> FindRecentExtension
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> find_recent
    find<span style="color: #990000">(:</span>all<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span><span style="color: #FF0000">"created_at &gt; ?"</span><span style="color: #990000">,</span> <span style="color: #993399">5</span><span style="color: #990000">.</span>days<span style="color: #990000">.</span>ago<span style="color: #990000">])</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>extend <span style="color: #990000">=&gt;</span> FindRecentExtension
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>deliveries<span style="color: #990000">,</span> <span style="color: #990000">:</span>extend <span style="color: #990000">=&gt;</span> FindRecentExtension
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>To include more than one extension module in a single association, specify an array of names:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>extend <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span>FindRecentExtension<span style="color: #990000">,</span> FindActiveExtension<span style="color: #990000">]</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Extensions can refer to the internals of the association proxy using these three accessors:</p></div>
<div class="ilist"><ul>
<li>
<p>
<tt>proxy_owner</tt> returns the object that the association is a part of.
</p>
</li>
<li>
<p>
<tt>proxy_reflection</tt> returns the reflection object that describes the association.
</p>
</li>
<li>
<p>
<tt>proxy_target</tt> returns the associated object for <tt>belongs_to</tt> or <tt>has_one</tt>, or the collection of associated objects for <tt>has_many</tt> or <tt>has_and_belongs_to_many</tt>.
</p>
</li>
</ul></div>
</div>
<h2 id="_changelog">5. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11">Lighthouse ticket</a></p></div>
<div class="ilist"><ul>
<li>
<p>
September 28, 2008: Corrected <tt>has_many :through</tt> diagram, added polymorphic diagram, some reorganization by <a href="../authors.html#mgunderloy">Mike Gunderloy</a> . First release version.
</p>
</li>
<li>
<p>
September 22, 2008: Added diagrams, misc. cleanup by <a href="../authors.html#mgunderloy">Mike Gunderloy</a> (not yet approved for publication)
</p>
</li>
<li>
<p>
September 14, 2008: initial version by <a href="../authors.html#mgunderloy">Mike Gunderloy</a> (not yet approved for publication)
</p>
</li>
</ul></div>
</div>

		</div>
	</div>
</body>
</html>