railties 3.0.10 → 3.0.11

Sign up to get free protection for your applications and to get access to all the features.
Files changed (170) hide show
  1. data/CHANGELOG +12 -1
  2. data/guides/output/2_2_release_notes.html +565 -0
  3. data/guides/output/2_3_release_notes.html +713 -0
  4. data/guides/output/3_0_release_notes.html +652 -0
  5. data/guides/output/3_1_release_notes.html +670 -0
  6. data/guides/output/action_controller_overview.html +925 -0
  7. data/guides/output/action_mailer_basics.html +658 -0
  8. data/guides/output/action_view_overview.html +1471 -0
  9. data/guides/output/active_model_basics.html +349 -0
  10. data/guides/output/active_record_basics.html +364 -0
  11. data/guides/output/active_record_querying.html +1272 -0
  12. data/guides/output/active_record_validations_callbacks.html +1292 -0
  13. data/guides/output/active_resource_basics.html +252 -0
  14. data/guides/output/active_support_core_extensions.html +3374 -0
  15. data/guides/output/ajax_on_rails.html +412 -0
  16. data/guides/output/api_documentation_guidelines.html +317 -0
  17. data/guides/output/asset_pipeline.html +691 -0
  18. data/guides/output/association_basics.html +1742 -0
  19. data/guides/output/caching_with_rails.html +533 -0
  20. data/guides/output/command_line.html +662 -0
  21. data/guides/output/configuring.html +811 -0
  22. data/guides/output/contribute.html +216 -0
  23. data/guides/output/contributing_to_ruby_on_rails.html +465 -0
  24. data/guides/output/credits.html +210 -0
  25. data/guides/output/debugging_rails_applications.html +791 -0
  26. data/guides/output/engines.html +673 -0
  27. data/guides/output/form_helpers.html +850 -0
  28. data/guides/output/generators.html +725 -0
  29. data/guides/output/getting_started.html +1980 -0
  30. data/guides/output/i18n.html +1054 -0
  31. data/guides/output/images/belongs_to.png +0 -0
  32. data/guides/output/images/book_icon.gif +0 -0
  33. data/guides/output/images/bullet.gif +0 -0
  34. data/guides/output/images/challenge.png +0 -0
  35. data/guides/output/images/chapters_icon.gif +0 -0
  36. data/guides/output/images/check_bullet.gif +0 -0
  37. data/guides/output/images/credits_pic_blank.gif +0 -0
  38. data/guides/output/images/csrf.png +0 -0
  39. data/guides/output/images/customized_error_messages.png +0 -0
  40. data/guides/output/images/edge_badge.png +0 -0
  41. data/guides/output/images/error_messages.png +0 -0
  42. data/guides/output/images/feature_tile.gif +0 -0
  43. data/guides/output/images/footer_tile.gif +0 -0
  44. data/guides/output/images/fxn.png +0 -0
  45. data/guides/output/images/grey_bullet.gif +0 -0
  46. data/guides/output/images/habtm.png +0 -0
  47. data/guides/output/images/has_many.png +0 -0
  48. data/guides/output/images/has_many_through.png +0 -0
  49. data/guides/output/images/has_one.png +0 -0
  50. data/guides/output/images/has_one_through.png +0 -0
  51. data/guides/output/images/header_backdrop.png +0 -0
  52. data/guides/output/images/header_tile.gif +0 -0
  53. data/guides/output/images/i18n/demo_html_safe.png +0 -0
  54. data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
  55. data/guides/output/images/i18n/demo_translated_en.png +0 -0
  56. data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
  57. data/guides/output/images/i18n/demo_translation_missing.png +0 -0
  58. data/guides/output/images/i18n/demo_untranslated.png +0 -0
  59. data/guides/output/images/icons/README +5 -0
  60. data/guides/output/images/icons/callouts/1.png +0 -0
  61. data/guides/output/images/icons/callouts/10.png +0 -0
  62. data/guides/output/images/icons/callouts/11.png +0 -0
  63. data/guides/output/images/icons/callouts/12.png +0 -0
  64. data/guides/output/images/icons/callouts/13.png +0 -0
  65. data/guides/output/images/icons/callouts/14.png +0 -0
  66. data/guides/output/images/icons/callouts/15.png +0 -0
  67. data/guides/output/images/icons/callouts/2.png +0 -0
  68. data/guides/output/images/icons/callouts/3.png +0 -0
  69. data/guides/output/images/icons/callouts/4.png +0 -0
  70. data/guides/output/images/icons/callouts/5.png +0 -0
  71. data/guides/output/images/icons/callouts/6.png +0 -0
  72. data/guides/output/images/icons/callouts/7.png +0 -0
  73. data/guides/output/images/icons/callouts/8.png +0 -0
  74. data/guides/output/images/icons/callouts/9.png +0 -0
  75. data/guides/output/images/icons/caution.png +0 -0
  76. data/guides/output/images/icons/example.png +0 -0
  77. data/guides/output/images/icons/home.png +0 -0
  78. data/guides/output/images/icons/important.png +0 -0
  79. data/guides/output/images/icons/next.png +0 -0
  80. data/guides/output/images/icons/note.png +0 -0
  81. data/guides/output/images/icons/prev.png +0 -0
  82. data/guides/output/images/icons/tip.png +0 -0
  83. data/guides/output/images/icons/up.png +0 -0
  84. data/guides/output/images/icons/warning.png +0 -0
  85. data/guides/output/images/jaimeiniesta.jpg +0 -0
  86. data/guides/output/images/nav_arrow.gif +0 -0
  87. data/guides/output/images/polymorphic.png +0 -0
  88. data/guides/output/images/posts_index.png +0 -0
  89. data/guides/output/images/radar.png +0 -0
  90. data/guides/output/images/rails_guides_logo.gif +0 -0
  91. data/guides/output/images/rails_logo_remix.gif +0 -0
  92. data/guides/output/images/rails_welcome.png +0 -0
  93. data/guides/output/images/session_fixation.png +0 -0
  94. data/guides/output/images/tab_grey.gif +0 -0
  95. data/guides/output/images/tab_info.gif +0 -0
  96. data/guides/output/images/tab_note.gif +0 -0
  97. data/guides/output/images/tab_red.gif +0 -0
  98. data/guides/output/images/tab_yellow.gif +0 -0
  99. data/guides/output/images/tab_yellow.png +0 -0
  100. data/guides/output/images/validation_error_messages.png +0 -0
  101. data/guides/output/images/vijaydev.jpg +0 -0
  102. data/guides/output/index.html +300 -0
  103. data/guides/output/initialization.html +1087 -0
  104. data/guides/output/javascripts/guides.js +7 -0
  105. data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
  106. data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
  107. data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
  108. data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
  109. data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
  110. data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
  111. data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
  112. data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
  113. data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
  114. data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
  115. data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
  116. data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
  117. data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
  118. data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
  119. data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
  120. data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
  121. data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
  122. data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
  123. data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
  124. data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
  125. data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
  126. data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
  127. data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
  128. data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
  129. data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
  130. data/guides/output/javascripts/syntaxhighlighter/shCore.js +17 -0
  131. data/guides/output/layout.html +312 -0
  132. data/guides/output/layouts_and_rendering.html +1257 -0
  133. data/guides/output/migrations.html +751 -0
  134. data/guides/output/nested_model_forms.html +350 -0
  135. data/guides/output/performance_testing.html +858 -0
  136. data/guides/output/plugins.html +590 -0
  137. data/guides/output/rails_application_templates.html +368 -0
  138. data/guides/output/rails_on_rack.html +408 -0
  139. data/guides/output/routing.html +1246 -0
  140. data/guides/output/ruby_on_rails_guides_guidelines.html +218 -0
  141. data/guides/output/security.html +968 -0
  142. data/guides/output/stylesheets/fixes.css +16 -0
  143. data/guides/output/stylesheets/main.css +445 -0
  144. data/guides/output/stylesheets/print.css +52 -0
  145. data/guides/output/stylesheets/reset.css +43 -0
  146. data/guides/output/stylesheets/style.css +13 -0
  147. data/guides/output/stylesheets/syntaxhighlighter/shCore.css +226 -0
  148. data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
  149. data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
  150. data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
  151. data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
  152. data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
  153. data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
  154. data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
  155. data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
  156. data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
  157. data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
  158. data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
  159. data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
  160. data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
  161. data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
  162. data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
  163. data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
  164. data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
  165. data/guides/output/testing.html +1182 -0
  166. data/lib/rails/generators/rails/app/app_generator.rb +1 -1
  167. data/lib/rails/generators/rails/app/templates/public/javascripts/rails.js +86 -75
  168. data/lib/rails/tasks/documentation.rake +1 -1
  169. data/lib/rails/version.rb +1 -1
  170. metadata +457 -293
@@ -0,0 +1,1742 @@
1
+ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
+
4
+ <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5
+ <head>
6
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
7
+
8
+ <title>Ruby on Rails Guides: A Guide to Active Record Associations</title>
9
+
10
+ <link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
11
+ <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
12
+
13
+ <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
14
+ <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
15
+
16
+ <link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
17
+ </head>
18
+ <body class="guide">
19
+ <div id="topNav">
20
+ <div class="wrapper">
21
+ <strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
22
+ <a href="http://rubyonrails.org/">Overview</a> |
23
+ <a href="http://rubyonrails.org/download">Download</a> |
24
+ <a href="http://rubyonrails.org/deploy">Deploy</a> |
25
+ <a href="https://github.com/rails/rails">Code</a> |
26
+ <a href="http://rubyonrails.org/screencasts">Screencasts</a> |
27
+ <a href="http://rubyonrails.org/documentation">Documentation</a> |
28
+ <a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
29
+ <a href="http://rubyonrails.org/community">Community</a> |
30
+ <a href="http://weblog.rubyonrails.org/">Blog</a>
31
+ </div>
32
+ </div>
33
+ <div id="header">
34
+ <div class="wrapper clearfix">
35
+ <h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
36
+ <p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
37
+ <ul class="nav">
38
+ <li><a href="index.html">Home</a></li>
39
+ <li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a>
40
+ <div id="guides" class="clearfix" style="display: none;">
41
+ <hr />
42
+ <dl class="L">
43
+ <dt>Start Here</dt>
44
+ <dd><a href="getting_started.html">Getting Started with Rails</a></dd>
45
+ <dt>Models</dt>
46
+ <dd><a href="migrations.html">Rails Database Migrations</a></dd>
47
+ <dd><a href="active_record_validations_callbacks.html">Active Record Validations and Callbacks</a></dd>
48
+ <dd><a href="association_basics.html">Active Record Associations</a></dd>
49
+ <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
50
+ <dt>Views</dt>
51
+ <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
52
+ <dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
53
+ <dt>Controllers</dt>
54
+ <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
55
+ <dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
56
+ </dl>
57
+ <dl class="R">
58
+ <dt>Digging Deeper</dt>
59
+ <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
60
+ <dd><a href="i18n.html">Rails Internationalization API</a></dd>
61
+ <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
62
+ <dd><a href="testing.html">Testing Rails Applications</a></dd>
63
+ <dd><a href="security.html">Securing Rails Applications</a></dd>
64
+ <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
65
+ <dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd>
66
+ <dd><a href="configuring.html">Configuring Rails Applications</a></dd>
67
+ <dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
68
+ <dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
69
+ <dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
70
+
71
+ <dt>Extending Rails</dt>
72
+ <dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
73
+ <dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
74
+ <dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
75
+
76
+ <dt>Contributing to Ruby on Rails</dt>
77
+ <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
78
+ <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
79
+ <dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
80
+
81
+ <dt>Release Notes</dt>
82
+ <dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
83
+ <dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
84
+ <dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
85
+ <dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
86
+ </dl>
87
+ </div>
88
+ </li>
89
+ <li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
90
+ <li><a href="credits.html">Credits</a></li>
91
+ </ul>
92
+ </div>
93
+ </div>
94
+ <hr class="hide" />
95
+
96
+ <div id="feature">
97
+ <div class="wrapper">
98
+ <h2>A Guide to Active Record Associations</h2>
99
+ <p>This guide covers the association features of Active Record. By referring to this guide, you will be able to:</p>
100
+ <ul>
101
+ <li>Declare associations between Active Record models</li>
102
+ <li>Understand the various types of Active Record associations</li>
103
+ <li>Use the methods added to your models by creating associations</li>
104
+ </ul>
105
+
106
+ <div id="subCol">
107
+ <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
108
+ <ol class="chapters">
109
+ <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-belongs_to-association">The <tt>belongs_to</tt> Association</a></li> <li><a href="#the-has_one-association">The <tt>has_one</tt> Association</a></li> <li><a href="#the-has_many-association">The <tt>has_many</tt> Association</a></li> <li><a href="#the-has_many-through-association">The <tt>has_many :through</tt> Association</a></li> <li><a href="#the-has_one-through-association">The <tt>has_one :through</tt> Association</a></li> <li><a href="#the-has_and_belongs_to_many-association">The <tt>has_and_belongs_to_many</tt> Association</a></li> <li><a href="#choosing-between-belongs_to-and-has_one">Choosing Between <tt>belongs_to</tt> and <tt>has_one</tt></a></li> <li><a href="#choosing-between-has_many-through-and-has_and_belongs_to_many">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="#belongs_to-association-reference"><tt>belongs_to</tt> Association Reference</a></li> <li><a href="#has_one-association-reference"><tt>has_one</tt> Association Reference</a></li> <li><a href="#has_many-association-reference"><tt>has_many</tt> Association Reference</a></li> <li><a href="#has_and_belongs_to_many-association-reference"><tt>has_and_belongs_to_many</tt> Association Reference</a></li> <li><a href="#association-callbacks">Association Callbacks</a></li> <li><a href="#association-extensions">Association Extensions</a></li></ul></li></ol></div>
110
+ </div>
111
+ </div>
112
+
113
+ <div id="container">
114
+ <div class="wrapper">
115
+ <div id="mainCol">
116
+ <h3 id="why-associations">1 Why Associations?</h3>
117
+ <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>
118
+ <div class="code_container">
119
+ <pre class="brush: ruby; gutter: false; toolbar: false">
120
+ class Customer &lt; ActiveRecord::Base
121
+ end
122
+
123
+ class Order &lt; ActiveRecord::Base
124
+ end
125
+ </pre>
126
+ </div>
127
+ <p>Now, suppose we wanted to add a new order for an existing customer. We&#8217;d need to do something like this:</p>
128
+ <div class="code_container">
129
+ <pre class="brush: ruby; gutter: false; toolbar: false">
130
+ @order = Order.create(:order_date =&gt; Time.now,
131
+ :customer_id =&gt; @customer.id)
132
+ </pre>
133
+ </div>
134
+ <p>Or consider deleting a customer, and ensuring that all of its orders get deleted as well:</p>
135
+ <div class="code_container">
136
+ <pre class="brush: ruby; gutter: false; toolbar: false">
137
+ @orders = Order.where(:customer_id =&gt; @customer.id)
138
+ @orders.each do |order|
139
+ order.destroy
140
+ end
141
+ @customer.destroy
142
+ </pre>
143
+ </div>
144
+ <p>With Active Record associations, we can streamline these &#8212; and other &#8212; operations by declaratively telling Rails that there is a connection between the two models. Here&#8217;s the revised code for setting up customers and orders:</p>
145
+ <div class="code_container">
146
+ <pre class="brush: ruby; gutter: false; toolbar: false">
147
+ class Customer &lt; ActiveRecord::Base
148
+ has_many :orders, :dependent =&gt; :destroy
149
+ end
150
+
151
+ class Order &lt; ActiveRecord::Base
152
+ belongs_to :customer
153
+ end
154
+ </pre>
155
+ </div>
156
+ <p>With this change, creating a new order for a particular customer is easier:</p>
157
+ <div class="code_container">
158
+ <pre class="brush: ruby; gutter: false; toolbar: false">
159
+ @order = @customer.orders.create(:order_date =&gt; Time.now)
160
+ </pre>
161
+ </div>
162
+ <p>Deleting a customer and all of its orders is <em>much</em> easier:</p>
163
+ <div class="code_container">
164
+ <pre class="brush: ruby; gutter: false; toolbar: false">
165
+ @customer.destroy
166
+ </pre>
167
+ </div>
168
+ <p>To learn more about the different types of associations, read the next section of this guide. That&#8217;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>
169
+ <h3 id="the-types-of-associations">2 The Types of Associations</h3>
170
+ <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 associations:</p>
171
+ <ul>
172
+ <li><tt>belongs_to</tt></li>
173
+ <li><tt>has_one</tt></li>
174
+ <li><tt>has_many</tt></li>
175
+ <li><tt>has_many :through</tt></li>
176
+ <li><tt>has_one :through</tt></li>
177
+ <li><tt>has_and_belongs_to_many</tt></li>
178
+ </ul>
179
+ <p>In the remainder of this guide, you&#8217;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>
180
+ <h4 id="the-belongs_to-association">2.1 The <tt>belongs_to</tt> Association</h4>
181
+ <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 &#8220;belongs to&#8221; 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&#8217;d declare the order model this way:</p>
182
+ <div class="code_container">
183
+ <pre class="brush: ruby; gutter: false; toolbar: false">
184
+ class Order &lt; ActiveRecord::Base
185
+ belongs_to :customer
186
+ end
187
+ </pre>
188
+ </div>
189
+ <p><img src="images/belongs_to.png" title="belongs_to Association Diagram" alt="belongs_to Association Diagram" /></p>
190
+ <h4 id="the-has_one-association">2.2 The <tt>has_one</tt> Association</h4>
191
+ <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&#8217;d declare the supplier model like this:</p>
192
+ <div class="code_container">
193
+ <pre class="brush: ruby; gutter: false; toolbar: false">
194
+ class Supplier &lt; ActiveRecord::Base
195
+ has_one :account
196
+ end
197
+ </pre>
198
+ </div>
199
+ <p><img src="images/has_one.png" title="has_one Association Diagram" alt="has_one Association Diagram" /></p>
200
+ <h4 id="the-has_many-association">2.3 The <tt>has_many</tt> Association</h4>
201
+ <p>A <tt>has_many</tt> association indicates a one-to-many connection with another model. You&#8217;ll often find this association on the &#8220;other side&#8221; 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>
202
+ <div class="code_container">
203
+ <pre class="brush: ruby; gutter: false; toolbar: false">
204
+ class Customer &lt; ActiveRecord::Base
205
+ has_many :orders
206
+ end
207
+ </pre>
208
+ </div>
209
+ <div class="note"><p>The name of the other model is pluralized when declaring a <tt>has_many</tt> association.</p></div>
210
+ <p><img src="images/has_many.png" title="has_many Association Diagram" alt="has_many Association Diagram" /></p>
211
+ <h4 id="the-has_many-through-association">2.4 The <tt>has_many :through</tt> Association</h4>
212
+ <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>
213
+ <div class="code_container">
214
+ <pre class="brush: ruby; gutter: false; toolbar: false">
215
+ class Physician &lt; ActiveRecord::Base
216
+ has_many :appointments
217
+ has_many :patients, :through =&gt; :appointments
218
+ end
219
+
220
+ class Appointment &lt; ActiveRecord::Base
221
+ belongs_to :physician
222
+ belongs_to :patient
223
+ end
224
+
225
+ class Patient &lt; ActiveRecord::Base
226
+ has_many :appointments
227
+ has_many :physicians, :through =&gt; :appointments
228
+ end
229
+ </pre>
230
+ </div>
231
+ <p><img src="images/has_many_through.png" title="has_many :through Association Diagram" alt="has_many :through Association Diagram" /></p>
232
+ <p>The collection of join models can be managed via the <span class="caps">API</span>. For example, if you assign</p>
233
+ <div class="code_container">
234
+ <pre class="brush: ruby; gutter: false; toolbar: false">
235
+ physician.patients = patients
236
+ </pre>
237
+ </div>
238
+ <p>new join models are created for newly associated objects, and if some are gone their rows are deleted.</p>
239
+ <div class="warning"><p>Automatic deletion of join models is direct, no destroy callbacks are triggered.</p></div>
240
+ <p>The <tt>has_many :through</tt> association is also useful for setting up &#8220;shortcuts&#8221; 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>
241
+ <div class="code_container">
242
+ <pre class="brush: ruby; gutter: false; toolbar: false">
243
+ class Document &lt; ActiveRecord::Base
244
+ has_many :sections
245
+ has_many :paragraphs, :through =&gt; :sections
246
+ end
247
+
248
+ class Section &lt; ActiveRecord::Base
249
+ belongs_to :document
250
+ has_many :paragraphs
251
+ end
252
+
253
+ class Paragraph &lt; ActiveRecord::Base
254
+ belongs_to :section
255
+ end
256
+ </pre>
257
+ </div>
258
+ <p>With <tt>:through => :sections</tt> specified, Rails will now understand:</p>
259
+ <div class="code_container">
260
+ <pre class="brush: ruby; gutter: false; toolbar: false">
261
+ @document.paragraphs
262
+ </pre>
263
+ </div>
264
+ <h4 id="the-has_one-through-association">2.5 The <tt>has_one :through</tt> Association</h4>
265
+ <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>
266
+ <div class="code_container">
267
+ <pre class="brush: ruby; gutter: false; toolbar: false">
268
+ class Supplier &lt; ActiveRecord::Base
269
+ has_one :account
270
+ has_one :account_history, :through =&gt; :account
271
+ end
272
+
273
+ class Account &lt; ActiveRecord::Base
274
+ belongs_to :supplier
275
+ has_one :account_history
276
+ end
277
+
278
+ class AccountHistory &lt; ActiveRecord::Base
279
+ belongs_to :account
280
+ end
281
+ </pre>
282
+ </div>
283
+ <p><img src="images/has_one_through.png" title="has_one :through Association Diagram" alt="has_one :through Association Diagram" /></p>
284
+ <h4 id="the-has_and_belongs_to_many-association">2.6 The <tt>has_and_belongs_to_many</tt> Association</h4>
285
+ <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>
286
+ <div class="code_container">
287
+ <pre class="brush: ruby; gutter: false; toolbar: false">
288
+ class Assembly &lt; ActiveRecord::Base
289
+ has_and_belongs_to_many :parts
290
+ end
291
+
292
+ class Part &lt; ActiveRecord::Base
293
+ has_and_belongs_to_many :assemblies
294
+ end
295
+ </pre>
296
+ </div>
297
+ <p><img src="images/habtm.png" title="has_and_belongs_to_many Association Diagram" alt="has_and_belongs_to_many Association Diagram" /></p>
298
+ <h4 id="choosing-between-belongs_to-and-has_one">2.7 Choosing Between <tt>belongs_to</tt> and <tt>has_one</tt></h4>
299
+ <p>If you want to set up a one-to-one relationship between two models, you&#8217;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>
300
+ <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 &#8211; 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>
301
+ <div class="code_container">
302
+ <pre class="brush: ruby; gutter: false; toolbar: false">
303
+ class Supplier &lt; ActiveRecord::Base
304
+ has_one :account
305
+ end
306
+
307
+ class Account &lt; ActiveRecord::Base
308
+ belongs_to :supplier
309
+ end
310
+ </pre>
311
+ </div>
312
+ <p>The corresponding migration might look like this:</p>
313
+ <div class="code_container">
314
+ <pre class="brush: ruby; gutter: false; toolbar: false">
315
+ class CreateSuppliers &lt; ActiveRecord::Migration
316
+ def change
317
+ create_table :suppliers do |t|
318
+ t.string :name
319
+ t.timestamps
320
+ end
321
+
322
+ create_table :accounts do |t|
323
+ t.integer :supplier_id
324
+ t.string :account_number
325
+ t.timestamps
326
+ end
327
+ end
328
+ end
329
+ </pre>
330
+ </div>
331
+ <div class="note"><p>Using <tt>t.integer :supplier_id</tt> makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using <tt>t.references :supplier</tt> instead.</p></div>
332
+ <h4 id="choosing-between-has_many-through-and-has_and_belongs_to_many">2.8 Choosing Between <tt>has_many :through</tt> and <tt>has_and_belongs_to_many</tt></h4>
333
+ <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>
334
+ <div class="code_container">
335
+ <pre class="brush: ruby; gutter: false; toolbar: false">
336
+ class Assembly &lt; ActiveRecord::Base
337
+ has_and_belongs_to_many :parts
338
+ end
339
+
340
+ class Part &lt; ActiveRecord::Base
341
+ has_and_belongs_to_many :assemblies
342
+ end
343
+ </pre>
344
+ </div>
345
+ <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>
346
+ <div class="code_container">
347
+ <pre class="brush: ruby; gutter: false; toolbar: false">
348
+ class Assembly &lt; ActiveRecord::Base
349
+ has_many :manifests
350
+ has_many :parts, :through =&gt; :manifests
351
+ end
352
+
353
+ class Manifest &lt; ActiveRecord::Base
354
+ belongs_to :assembly
355
+ belongs_to :part
356
+ end
357
+
358
+ class Part &lt; ActiveRecord::Base
359
+ has_many :manifests
360
+ has_many :assemblies, :through =&gt; :manifests
361
+ end
362
+ </pre>
363
+ </div>
364
+ <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&#8217;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&#8217;ll need to remember to create the joining table in the database).</p>
365
+ <p>You should use <tt>has_many :through</tt> if you need validations, callbacks, or extra attributes on the join model.</p>
366
+ <h4 id="polymorphic-associations">2.9 Polymorphic Associations</h4>
367
+ <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&#8217;s how this could be declared:</p>
368
+ <div class="code_container">
369
+ <pre class="brush: ruby; gutter: false; toolbar: false">
370
+ class Picture &lt; ActiveRecord::Base
371
+ belongs_to :imageable, :polymorphic =&gt; true
372
+ end
373
+
374
+ class Employee &lt; ActiveRecord::Base
375
+ has_many :pictures, :as =&gt; :imageable
376
+ end
377
+
378
+ class Product &lt; ActiveRecord::Base
379
+ has_many :pictures, :as =&gt; :imageable
380
+ end
381
+ </pre>
382
+ </div>
383
+ <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>.</p>
384
+ <p>Similarly, you can retrieve <tt>@product.pictures</tt>.</p>
385
+ <p>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>
386
+ <div class="code_container">
387
+ <pre class="brush: ruby; gutter: false; toolbar: false">
388
+ class CreatePictures &lt; ActiveRecord::Migration
389
+ def change
390
+ create_table :pictures do |t|
391
+ t.string :name
392
+ t.integer :imageable_id
393
+ t.string :imageable_type
394
+ t.timestamps
395
+ end
396
+ end
397
+ end
398
+ </pre>
399
+ </div>
400
+ <p>This migration can be simplified by using the <tt>t.references</tt> form:</p>
401
+ <div class="code_container">
402
+ <pre class="brush: ruby; gutter: false; toolbar: false">
403
+ class CreatePictures &lt; ActiveRecord::Migration
404
+ def change
405
+ create_table :pictures do |t|
406
+ t.string :name
407
+ t.references :imageable, :polymorphic =&gt; true
408
+ t.timestamps
409
+ end
410
+ end
411
+ end
412
+ </pre>
413
+ </div>
414
+ <p><img src="images/polymorphic.png" title="Polymorphic Association Diagram" alt="Polymorphic Association Diagram" /></p>
415
+ <h4 id="self-joins">2.10 Self Joins</h4>
416
+ <p>In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:</p>
417
+ <div class="code_container">
418
+ <pre class="brush: ruby; gutter: false; toolbar: false">
419
+ class Employee &lt; ActiveRecord::Base
420
+ has_many :subordinates, :class_name =&gt; &quot;Employee&quot;
421
+ belongs_to :manager, :class_name =&gt; &quot;Employee&quot;,
422
+ :foreign_key =&gt; &quot;manager_id&quot;
423
+ end
424
+ </pre>
425
+ </div>
426
+ <p>With this setup, you can retrieve <tt>@employee.subordinates</tt> and <tt>@employee.manager</tt>.</p>
427
+ <h3 id="tips-tricks-and-warnings">3 Tips, Tricks, and Warnings</h3>
428
+ <p>Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:</p>
429
+ <ul>
430
+ <li>Controlling caching</li>
431
+ <li>Avoiding name collisions</li>
432
+ <li>Updating the schema</li>
433
+ <li>Controlling association scope</li>
434
+ </ul>
435
+ <h4 id="controlling-caching">3.1 Controlling Caching</h4>
436
+ <p>All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:</p>
437
+ <div class="code_container">
438
+ <pre class="brush: ruby; gutter: false; toolbar: false">
439
+ customer.orders # retrieves orders from the database
440
+ customer.orders.size # uses the cached copy of orders
441
+ customer.orders.empty? # uses the cached copy of orders
442
+ </pre>
443
+ </div>
444
+ <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>
445
+ <div class="code_container">
446
+ <pre class="brush: ruby; gutter: false; toolbar: false">
447
+ customer.orders # retrieves orders from the database
448
+ customer.orders.size # uses the cached copy of orders
449
+ customer.orders(true).empty? # discards the cached copy of orders
450
+ # and goes back to the database
451
+ </pre>
452
+ </div>
453
+ <h4 id="avoiding-name-collisions">3.2 Avoiding Name Collisions</h4>
454
+ <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>
455
+ <h4 id="updating-the-schema">3.3 Updating the Schema</h4>
456
+ <p>Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For <tt>belongs_to</tt> associations you need to create foreign keys, and for <tt>has_and_belongs_to_many</tt> associations you need to create the appropriate join table.</p>
457
+ <h5 id="creating-foreign-keys-for-belongs_to-associations">3.3.1 Creating Foreign Keys for <tt>belongs_to</tt> Associations</h5>
458
+ <p>When you declare a <tt>belongs_to</tt> association, you need to create foreign keys as appropriate. For example, consider this model:</p>
459
+ <div class="code_container">
460
+ <pre class="brush: ruby; gutter: false; toolbar: false">
461
+ class Order &lt; ActiveRecord::Base
462
+ belongs_to :customer
463
+ end
464
+ </pre>
465
+ </div>
466
+ <p>This declaration needs to be backed up by the proper foreign key declaration on the orders table:</p>
467
+ <div class="code_container">
468
+ <pre class="brush: ruby; gutter: false; toolbar: false">
469
+ class CreateOrders &lt; ActiveRecord::Migration
470
+ def change
471
+ create_table :orders do |t|
472
+ t.datetime :order_date
473
+ t.string :order_number
474
+ t.integer :customer_id
475
+ end
476
+ end
477
+ end
478
+ </pre>
479
+ </div>
480
+ <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>
481
+ <h5 id="creating-join-tables-for-has_and_belongs_to_many-associations">3.3.2 Creating Join Tables for <tt>has_and_belongs_to_many</tt> Associations</h5>
482
+ <p>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 creates 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 &#8220;customers_orders&#8221; because &#8220;c&#8221; outranks &#8220;o&#8221; in lexical ordering.</p>
483
+ <div class="warning"><p>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 &#8220;paper_boxes&#8221; and &#8220;papers&#8221; to generate a join table name of &#8220;papers_paper_boxes&#8221; because of the length of the name &#8220;paper_boxes&#8221;, but it in fact generates a join table name of &#8220;paper_boxes_papers&#8221; (because the underscore &#8216;_&#8217; is lexicographically <em>less</em> than &#8216;s&#8217; in common encodings).</p></div>
484
+ <p>Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:</p>
485
+ <div class="code_container">
486
+ <pre class="brush: ruby; gutter: false; toolbar: false">
487
+ class Assembly &lt; ActiveRecord::Base
488
+ has_and_belongs_to_many :parts
489
+ end
490
+
491
+ class Part &lt; ActiveRecord::Base
492
+ has_and_belongs_to_many :assemblies
493
+ end
494
+ </pre>
495
+ </div>
496
+ <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>
497
+ <div class="code_container">
498
+ <pre class="brush: ruby; gutter: false; toolbar: false">
499
+ class CreateAssemblyPartJoinTable &lt; ActiveRecord::Migration
500
+ def change
501
+ create_table :assemblies_parts, :id =&gt; false do |t|
502
+ t.integer :assembly_id
503
+ t.integer :part_id
504
+ end
505
+ end
506
+ end
507
+ </pre>
508
+ </div>
509
+ <p>We pass <tt>:id => false</tt> to <tt>create_table</tt> because that table does not represent a model. That&#8217;s required for the association to work properly. If you observe any strange behavior in a <tt>has_and_belongs_to_many</tt> association like mangled models IDs, or exceptions about conflicting IDs chances are you forgot that bit.</p>
510
+ <h4 id="controlling-association-scope">3.4 Controlling Association Scope</h4>
511
+ <p>By default, associations look for objects only within the current module&#8217;s scope. This can be important when you declare Active Record models within a module. For example:</p>
512
+ <div class="code_container">
513
+ <pre class="brush: ruby; gutter: false; toolbar: false">
514
+ module MyApplication
515
+ module Business
516
+ class Supplier &lt; ActiveRecord::Base
517
+ has_one :account
518
+ end
519
+
520
+ class Account &lt; ActiveRecord::Base
521
+ belongs_to :supplier
522
+ end
523
+ end
524
+ end
525
+ </pre>
526
+ </div>
527
+ <p>This will work fine, because both the <tt>Supplier</tt> and the <tt>Account</tt> class are defined within the same scope. But the following will <em>not</em> work, because <tt>Supplier</tt> and <tt>Account</tt> are defined in different scopes:</p>
528
+ <div class="code_container">
529
+ <pre class="brush: ruby; gutter: false; toolbar: false">
530
+ module MyApplication
531
+ module Business
532
+ class Supplier &lt; ActiveRecord::Base
533
+ has_one :account
534
+ end
535
+ end
536
+
537
+ module Billing
538
+ class Account &lt; ActiveRecord::Base
539
+ belongs_to :supplier
540
+ end
541
+ end
542
+ end
543
+ </pre>
544
+ </div>
545
+ <p>To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:</p>
546
+ <div class="code_container">
547
+ <pre class="brush: ruby; gutter: false; toolbar: false">
548
+ module MyApplication
549
+ module Business
550
+ class Supplier &lt; ActiveRecord::Base
551
+ has_one :account,
552
+ :class_name =&gt; &quot;MyApplication::Billing::Account&quot;
553
+ end
554
+ end
555
+
556
+ module Billing
557
+ class Account &lt; ActiveRecord::Base
558
+ belongs_to :supplier,
559
+ :class_name =&gt; &quot;MyApplication::Business::Supplier&quot;
560
+ end
561
+ end
562
+ end
563
+ </pre>
564
+ </div>
565
+ <h3 id="detailed-association-reference">4 Detailed Association Reference</h3>
566
+ <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>
567
+ <h4 id="belongs_to-association-reference">4.1 <tt>belongs_to</tt> Association Reference</h4>
568
+ <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>
569
+ <h5 id="methods-added-by-belongs_to">4.1.1 Methods Added by <tt>belongs_to</tt></h5>
570
+ <p>When you declare a <tt>belongs_to</tt> association, the declaring class automatically gains four methods related to the association:</p>
571
+ <ul>
572
+ <li><tt><em>association</em>(force_reload = false)</tt></li>
573
+ <li><tt><em>association</em>=(associate)</tt></li>
574
+ <li><tt>build_<em>association</em>(attributes = {})</tt></li>
575
+ <li><tt>create_<em>association</em>(attributes = {})</tt></li>
576
+ </ul>
577
+ <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>
578
+ <div class="code_container">
579
+ <pre class="brush: ruby; gutter: false; toolbar: false">
580
+ class Order &lt; ActiveRecord::Base
581
+ belongs_to :customer
582
+ end
583
+ </pre>
584
+ </div>
585
+ <p>Each instance of the order model will have these methods:</p>
586
+ <div class="code_container">
587
+ <pre class="brush: ruby; gutter: false; toolbar: false">
588
+ customer
589
+ customer=
590
+ build_customer
591
+ create_customer
592
+ </pre>
593
+ </div>
594
+ <div class="note"><p>When initializing a new <tt>has_one</tt> or <tt>belongs_to</tt> association you must use the <tt>build_</tt> prefix to build the association, rather than the <tt>association.build</tt> method that would be used for <tt>has_many</tt> or <tt>has_and_belongs_to_many</tt> associations. To create one, use the <tt>create_</tt> prefix.</p></div>
595
+ <h6 id="belongs_to-association">4.1.1.1 <tt><em>association</em>(force_reload = false)</tt></h6>
596
+ <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>
597
+ <div class="code_container">
598
+ <pre class="brush: ruby; gutter: false; toolbar: false">
599
+ @customer = @order.customer
600
+ </pre>
601
+ </div>
602
+ <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>
603
+ <h6 id="belongs_to-association_equal">4.1.1.2 <tt><em>association</em>=(associate)</tt></h6>
604
+ <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&#8217;s foreign key to the same value.</p>
605
+ <div class="code_container">
606
+ <pre class="brush: ruby; gutter: false; toolbar: false">
607
+ @order.customer = @customer
608
+ </pre>
609
+ </div>
610
+ <h6 id="belongs_to-build_association">4.1.1.3 <tt>build_<em>association</em>(attributes = {})</tt></h6>
611
+ <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&#8217;s foreign key will be set, but the associated object will <em>not</em> yet be saved.</p>
612
+ <div class="code_container">
613
+ <pre class="brush: ruby; gutter: false; toolbar: false">
614
+ @customer = @order.build_customer(:customer_number =&gt; 123,
615
+ :customer_name =&gt; &quot;John Doe&quot;)
616
+ </pre>
617
+ </div>
618
+ <h6 id="belongs_to-create_association">4.1.1.4 <tt>create_<em>association</em>(attributes = {})</tt></h6>
619
+ <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, the link through this object&#8217;s foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object <em>will</em> be saved.</p>
620
+ <div class="code_container">
621
+ <pre class="brush: ruby; gutter: false; toolbar: false">
622
+ @customer = @order.create_customer(:customer_number =&gt; 123,
623
+ :customer_name =&gt; &quot;John Doe&quot;)
624
+ </pre>
625
+ </div>
626
+ <h5 id="options-for-belongs_to">4.1.2 Options for <tt>belongs_to</tt></h5>
627
+ <p>While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the <tt>belongs_to</tt> association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:</p>
628
+ <div class="code_container">
629
+ <pre class="brush: ruby; gutter: false; toolbar: false">
630
+ class Order &lt; ActiveRecord::Base
631
+ belongs_to :customer, :counter_cache =&gt; true,
632
+ :conditions =&gt; &quot;active = 1&quot;
633
+ end
634
+ </pre>
635
+ </div>
636
+ <p>The <tt>belongs_to</tt> association supports these options:</p>
637
+ <ul>
638
+ <li><tt>:autosave</tt></li>
639
+ <li><tt>:class_name</tt></li>
640
+ <li><tt>:conditions</tt></li>
641
+ <li><tt>:counter_cache</tt></li>
642
+ <li><tt>:dependent</tt></li>
643
+ <li><tt>:foreign_key</tt></li>
644
+ <li><tt>:include</tt></li>
645
+ <li><tt>:polymorphic</tt></li>
646
+ <li><tt>:readonly</tt></li>
647
+ <li><tt>:select</tt></li>
648
+ <li><tt>:touch</tt></li>
649
+ <li><tt>:validate</tt></li>
650
+ </ul>
651
+ <h6 id="belongs_to-autosave">4.1.2.1 <tt>:autosave</tt></h6>
652
+ <p>If you set the <tt>:autosave</tt> option to <tt>true</tt>, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.</p>
653
+ <h6 id="belongs_to-class_name">4.1.2.2 <tt>:class_name</tt></h6>
654
+ <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&#8217;d set things up this way:</p>
655
+ <div class="code_container">
656
+ <pre class="brush: ruby; gutter: false; toolbar: false">
657
+ class Order &lt; ActiveRecord::Base
658
+ belongs_to :customer, :class_name =&gt; &quot;Patron&quot;
659
+ end
660
+ </pre>
661
+ </div>
662
+ <h6 id="belongs_to-conditions">4.1.2.3 <tt>:conditions</tt></h6>
663
+ <p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by an <span class="caps">SQL</span> <tt>WHERE</tt> clause).</p>
664
+ <div class="code_container">
665
+ <pre class="brush: ruby; gutter: false; toolbar: false">
666
+ class Order &lt; ActiveRecord::Base
667
+ belongs_to :customer, :conditions =&gt; &quot;active = 1&quot;
668
+ end
669
+ </pre>
670
+ </div>
671
+ <h6 id="belongs_to-counter_cache">4.1.2.4 <tt>:counter_cache</tt></h6>
672
+ <p>The <tt>:counter_cache</tt> option can be used to make finding the number of belonging objects more efficient. Consider these models:</p>
673
+ <div class="code_container">
674
+ <pre class="brush: ruby; gutter: false; toolbar: false">
675
+ class Order &lt; ActiveRecord::Base
676
+ belongs_to :customer
677
+ end
678
+ class Customer &lt; ActiveRecord::Base
679
+ has_many :orders
680
+ end
681
+ </pre>
682
+ </div>
683
+ <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>
684
+ <div class="code_container">
685
+ <pre class="brush: ruby; gutter: false; toolbar: false">
686
+ class Order &lt; ActiveRecord::Base
687
+ belongs_to :customer, :counter_cache =&gt; true
688
+ end
689
+ class Customer &lt; ActiveRecord::Base
690
+ has_many :orders
691
+ end
692
+ </pre>
693
+ </div>
694
+ <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>
695
+ <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>
696
+ <div class="code_container">
697
+ <pre class="brush: ruby; gutter: false; toolbar: false">
698
+ class Order &lt; ActiveRecord::Base
699
+ belongs_to :customer, :counter_cache =&gt; :count_of_orders
700
+ end
701
+ class Customer &lt; ActiveRecord::Base
702
+ has_many :orders
703
+ end
704
+ </pre>
705
+ </div>
706
+ <p>Counter cache columns are added to the containing model&#8217;s list of read-only attributes through <tt>attr_readonly</tt>.</p>
707
+ <h6 id="belongs_to-dependent">4.1.2.5 <tt>:dependent</tt></h6>
708
+ <p>If you set the <tt>:dependent</tt> option to <tt>:destroy</tt>, then deleting this object will call the <tt>destroy</tt> 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>
709
+ <div class="warning"><p>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.</p></div>
710
+ <h6 id="belongs_to-foreign_key">4.1.2.6 <tt>:foreign_key</tt></h6>
711
+ <p>By convention, Rails assumes that the column used to hold the foreign key on this model is the name of the association with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p>
712
+ <div class="code_container">
713
+ <pre class="brush: ruby; gutter: false; toolbar: false">
714
+ class Order &lt; ActiveRecord::Base
715
+ belongs_to :customer, :class_name =&gt; &quot;Patron&quot;,
716
+ :foreign_key =&gt; &quot;patron_id&quot;
717
+ end
718
+ </pre>
719
+ </div>
720
+ <div class="info"><p>In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.</p></div>
721
+ <h6 id="belongs_to-includes">4.1.2.7 <tt>:include</tt></h6>
722
+ <p>You can use the <tt>:include</tt> option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p>
723
+ <div class="code_container">
724
+ <pre class="brush: ruby; gutter: false; toolbar: false">
725
+ class LineItem &lt; ActiveRecord::Base
726
+ belongs_to :order
727
+ end
728
+
729
+ class Order &lt; ActiveRecord::Base
730
+ belongs_to :customer
731
+ has_many :line_items
732
+ end
733
+
734
+ class Customer &lt; ActiveRecord::Base
735
+ has_many :orders
736
+ end
737
+ </pre>
738
+ </div>
739
+ <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>
740
+ <div class="code_container">
741
+ <pre class="brush: ruby; gutter: false; toolbar: false">
742
+ class LineItem &lt; ActiveRecord::Base
743
+ belongs_to :order, :include =&gt; :customer
744
+ end
745
+
746
+ class Order &lt; ActiveRecord::Base
747
+ belongs_to :customer
748
+ has_many :line_items
749
+ end
750
+
751
+ class Customer &lt; ActiveRecord::Base
752
+ has_many :orders
753
+ end
754
+ </pre>
755
+ </div>
756
+ <div class="note"><p>There&#8217;s no need to use <tt>:include</tt> for immediate associations &#8211; that is, if you have <tt>Order belongs_to :customer</tt>, then the customer is eager-loaded automatically when it&#8217;s needed.</p></div>
757
+ <h6 id="belongs_to-polymorphic">4.1.2.8 <tt>:polymorphic</tt></h6>
758
+ <p>Passing <tt>true</tt> to the <tt>:polymorphic</tt> option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.</p>
759
+ <h6 id="belongs_to-readonly">4.1.2.9 <tt>:readonly</tt></h6>
760
+ <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>
761
+ <h6 id="belongs_to-select">4.1.2.10 <tt>:select</tt></h6>
762
+ <p>The <tt>:select</tt> option lets you override the <span class="caps">SQL</span> <tt>SELECT</tt> clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.</p>
763
+ <div class="info"><p>If you set the <tt>:select</tt> option on a <tt>belongs_to</tt> association, you should also set the <tt>foreign_key</tt> option to guarantee the correct results.</p></div>
764
+ <h6 id="belongs_to-touch">4.1.2.11 <tt>:touch</tt></h6>
765
+ <p>If you set the <tt>:touch</tt> option to <tt>:true</tt>, then the <tt>updated_at</tt> or <tt>updated_on</tt> timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:</p>
766
+ <div class="code_container">
767
+ <pre class="brush: ruby; gutter: false; toolbar: false">
768
+ class Order &lt; ActiveRecord::Base
769
+ belongs_to :customer, :touch =&gt; true
770
+ end
771
+
772
+ class Customer &lt; ActiveRecord::Base
773
+ has_many :orders
774
+ end
775
+ </pre>
776
+ </div>
777
+ <p>In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:</p>
778
+ <div class="code_container">
779
+ <pre class="brush: ruby; gutter: false; toolbar: false">
780
+ class Order &lt; ActiveRecord::Base
781
+ belongs_to :customer, :touch =&gt; :orders_updated_at
782
+ end
783
+ </pre>
784
+ </div>
785
+ <h6 id="belongs_to-validate">4.1.2.12 <tt>:validate</tt></h6>
786
+ <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>
787
+ <h5 id="belongs_to-do_any_associated_objects_exist">4.1.3 Do Any Associated Objects Exist?</h5>
788
+ <p>You can see if any associated objects exist by using the <tt><em>association</em>.nil?</tt> method:</p>
789
+ <div class="code_container">
790
+ <pre class="brush: ruby; gutter: false; toolbar: false">
791
+ if @order.customer.nil?
792
+ @msg = &quot;No customer found for this order&quot;
793
+ end
794
+ </pre>
795
+ </div>
796
+ <h5 id="belongs_to-when_are_objects_saved">4.1.4 When are Objects Saved?</h5>
797
+ <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>
798
+ <h4 id="has_one-association-reference">4.2 <tt>has_one</tt> Association Reference</h4>
799
+ <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>
800
+ <h5 id="methods-added-by-has_one">4.2.1 Methods Added by <tt>has_one</tt></h5>
801
+ <p>When you declare a <tt>has_one</tt> association, the declaring class automatically gains four methods related to the association:</p>
802
+ <ul>
803
+ <li><tt><em>association</em>(force_reload = false)</tt></li>
804
+ <li><tt><em>association</em>=(associate)</tt></li>
805
+ <li><tt>build_<em>association</em>(attributes = {})</tt></li>
806
+ <li><tt>create_<em>association</em>(attributes = {})</tt></li>
807
+ </ul>
808
+ <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>
809
+ <div class="code_container">
810
+ <pre class="brush: ruby; gutter: false; toolbar: false">
811
+ class Supplier &lt; ActiveRecord::Base
812
+ has_one :account
813
+ end
814
+ </pre>
815
+ </div>
816
+ <p>Each instance of the <tt>Supplier</tt> model will have these methods:</p>
817
+ <div class="code_container">
818
+ <pre class="brush: ruby; gutter: false; toolbar: false">
819
+ account
820
+ account=
821
+ build_account
822
+ create_account
823
+ </pre>
824
+ </div>
825
+ <div class="note"><p>When initializing a new <tt>has_one</tt> or <tt>belongs_to</tt> association you must use the <tt>build_</tt> prefix to build the association, rather than the <tt>association.build</tt> method that would be used for <tt>has_many</tt> or <tt>has_and_belongs_to_many</tt> associations. To create one, use the <tt>create_</tt> prefix.</p></div>
826
+ <h6 id="has_one-association">4.2.1.1 <tt><em>association</em>(force_reload = false)</tt></h6>
827
+ <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>
828
+ <div class="code_container">
829
+ <pre class="brush: ruby; gutter: false; toolbar: false">
830
+ @account = @supplier.account
831
+ </pre>
832
+ </div>
833
+ <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>
834
+ <h6 id="has_one-association_equal">4.2.1.2 <tt><em>association</em>=(associate)</tt></h6>
835
+ <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&#8217;s foreign key to the same value.</p>
836
+ <div class="code_container">
837
+ <pre class="brush: ruby; gutter: false; toolbar: false">
838
+ @supplier.account = @account
839
+ </pre>
840
+ </div>
841
+ <h6 id="has_one-build_association">4.2.1.3 <tt>build_<em>association</em>(attributes = {})</tt></h6>
842
+ <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 <em>not</em> yet be saved.</p>
843
+ <div class="code_container">
844
+ <pre class="brush: ruby; gutter: false; toolbar: false">
845
+ @account = @supplier.build_account(:terms =&gt; &quot;Net 30&quot;)
846
+ </pre>
847
+ </div>
848
+ <h6 id="has_one-create_association">4.2.1.4 <tt>create_<em>association</em>(attributes = {})</tt></h6>
849
+ <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, the link through its foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object <em>will</em> be saved.</p>
850
+ <div class="code_container">
851
+ <pre class="brush: ruby; gutter: false; toolbar: false">
852
+ @account = @supplier.create_account(:terms =&gt; &quot;Net 30&quot;)
853
+ </pre>
854
+ </div>
855
+ <h5 id="options-for-has_one">4.2.2 Options for <tt>has_one</tt></h5>
856
+ <p>While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the <tt>has_one</tt> association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:</p>
857
+ <div class="code_container">
858
+ <pre class="brush: ruby; gutter: false; toolbar: false">
859
+ class Supplier &lt; ActiveRecord::Base
860
+ has_one :account, :class_name =&gt; &quot;Billing&quot;, :dependent =&gt; :nullify
861
+ end
862
+ </pre>
863
+ </div>
864
+ <p>The <tt>has_one</tt> association supports these options:</p>
865
+ <ul>
866
+ <li><tt>:as</tt></li>
867
+ <li><tt>:autosave</tt></li>
868
+ <li><tt>:class_name</tt></li>
869
+ <li><tt>:conditions</tt></li>
870
+ <li><tt>:dependent</tt></li>
871
+ <li><tt>:foreign_key</tt></li>
872
+ <li><tt>:include</tt></li>
873
+ <li><tt>:order</tt></li>
874
+ <li><tt>:primary_key</tt></li>
875
+ <li><tt>:readonly</tt></li>
876
+ <li><tt>:select</tt></li>
877
+ <li><tt>:source</tt></li>
878
+ <li><tt>:source_type</tt></li>
879
+ <li><tt>:through</tt></li>
880
+ <li><tt>:validate</tt></li>
881
+ </ul>
882
+ <h6 id="has_one-as">4.2.2.1 <tt>:as</tt></h6>
883
+ <p>Setting the <tt>:as</tt> option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.</p>
884
+ <h6 id="has_one-autosave">4.2.2.2 <tt>:autosave</tt></h6>
885
+ <p>If you set the <tt>:autosave</tt> option to <tt>true</tt>, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.</p>
886
+ <h6 id="has_one-class_name">4.2.2.3 <tt>:class_name</tt></h6>
887
+ <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 <tt>Billing</tt>, you&#8217;d set things up this way:</p>
888
+ <div class="code_container">
889
+ <pre class="brush: ruby; gutter: false; toolbar: false">
890
+ class Supplier &lt; ActiveRecord::Base
891
+ has_one :account, :class_name =&gt; &quot;Billing&quot;
892
+ end
893
+ </pre>
894
+ </div>
895
+ <h6 id="has_one-conditions">4.2.2.4 <tt>:conditions</tt></h6>
896
+ <p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by an <span class="caps">SQL</span> <tt>WHERE</tt> clause).</p>
897
+ <div class="code_container">
898
+ <pre class="brush: ruby; gutter: false; toolbar: false">
899
+ class Supplier &lt; ActiveRecord::Base
900
+ has_one :account, :conditions =&gt; &quot;confirmed = 1&quot;
901
+ end
902
+ </pre>
903
+ </div>
904
+ <h6 id="has_one-dependent">4.2.2.5 <tt>:dependent</tt></h6>
905
+ <p>If you set the <tt>:dependent</tt> option to <tt>:destroy</tt>, then deleting this object will call the <tt>destroy</tt> 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>
906
+ <h6 id="has_one-foreign_key">4.2.2.6 <tt>:foreign_key</tt></h6>
907
+ <p>By convention, Rails assumes 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>
908
+ <div class="code_container">
909
+ <pre class="brush: ruby; gutter: false; toolbar: false">
910
+ class Supplier &lt; ActiveRecord::Base
911
+ has_one :account, :foreign_key =&gt; &quot;supp_id&quot;
912
+ end
913
+ </pre>
914
+ </div>
915
+ <div class="info"><p>In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.</p></div>
916
+ <h6 id="has_one-include">4.2.2.7 <tt>:include</tt></h6>
917
+ <p>You can use the <tt>:include</tt> option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p>
918
+ <div class="code_container">
919
+ <pre class="brush: ruby; gutter: false; toolbar: false">
920
+ class Supplier &lt; ActiveRecord::Base
921
+ has_one :account
922
+ end
923
+
924
+ class Account &lt; ActiveRecord::Base
925
+ belongs_to :supplier
926
+ belongs_to :representative
927
+ end
928
+
929
+ class Representative &lt; ActiveRecord::Base
930
+ has_many :accounts
931
+ end
932
+ </pre>
933
+ </div>
934
+ <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>
935
+ <div class="code_container">
936
+ <pre class="brush: ruby; gutter: false; toolbar: false">
937
+ class Supplier &lt; ActiveRecord::Base
938
+ has_one :account, :include =&gt; :representative
939
+ end
940
+
941
+ class Account &lt; ActiveRecord::Base
942
+ belongs_to :supplier
943
+ belongs_to :representative
944
+ end
945
+
946
+ class Representative &lt; ActiveRecord::Base
947
+ has_many :accounts
948
+ end
949
+ </pre>
950
+ </div>
951
+ <h6 id="has_one-order">4.2.2.8 <tt>:order</tt></h6>
952
+ <p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by an <span class="caps">SQL</span> <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>
953
+ <h6 id="has_one-primary_key">4.2.2.9 <tt>:primary_key</tt></h6>
954
+ <p>By convention, Rails assumes 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>
955
+ <h6 id="has_one-readonly">4.2.2.10 <tt>:readonly</tt></h6>
956
+ <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>
957
+ <h6 id="has_one-select">4.2.2.11 <tt>:select</tt></h6>
958
+ <p>The <tt>:select</tt> option lets you override the <span class="caps">SQL</span> <tt>SELECT</tt> clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.</p>
959
+ <h6 id="has_one-source">4.2.2.12 <tt>:source</tt></h6>
960
+ <p>The <tt>:source</tt> option specifies the source association name for a <tt>has_one :through</tt> association.</p>
961
+ <h6 id="has_one-source_type">4.2.2.13 <tt>:source_type</tt></h6>
962
+ <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>
963
+ <h6 id="has_one-through">4.2.2.14 <tt>:through</tt></h6>
964
+ <p>The <tt>:through</tt> option specifies a join model through which to perform the query. <tt>has_one :through</tt> associations were discussed in detail <a href="#the-has_one-through-association">earlier in this guide</a>.</p>
965
+ <h6 id="has_one-validate">4.2.2.15 <tt>:validate</tt></h6>
966
+ <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>
967
+ <h5 id="has_one-do_any_associated_objects_exist">4.2.3 Do Any Associated Objects Exist?</h5>
968
+ <p>You can see if any associated objects exist by using the <tt><em>association</em>.nil?</tt> method:</p>
969
+ <div class="code_container">
970
+ <pre class="brush: ruby; gutter: false; toolbar: false">
971
+ if @supplier.account.nil?
972
+ @msg = &quot;No account found for this supplier&quot;
973
+ end
974
+ </pre>
975
+ </div>
976
+ <h5 id="has_one-when_are_objects_saved">4.2.4 When are Objects Saved?</h5>
977
+ <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>
978
+ <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>
979
+ <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. They will automatically when the parent object is saved.</p>
980
+ <p>If you want to assign an object to a <tt>has_one</tt> association without saving the object, use the <tt><em>association</em>.build</tt> method.</p>
981
+ <h4 id="has_many-association-reference">4.3 <tt>has_many</tt> Association Reference</h4>
982
+ <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>
983
+ <h5 id="methods-added-by-has_many">4.3.1 Methods Added by <tt>has_many</tt></h5>
984
+ <p>When you declare a <tt>has_many</tt> association, the declaring class automatically gains 13 methods related to the association:</p>
985
+ <ul>
986
+ <li><tt><em>collection</em>(force_reload = false)</tt></li>
987
+ <li><tt><em>collection</em>&lt;&lt;(object, &#8230;)</tt></li>
988
+ <li><tt><em>collection</em>.delete(object, &#8230;)</tt></li>
989
+ <li><tt><em>collection</em>=objects</tt></li>
990
+ <li><tt><em>collection_singular</em>_ids</tt></li>
991
+ <li><tt><em>collection_singular</em>_ids=ids</tt></li>
992
+ <li><tt><em>collection</em>.clear</tt></li>
993
+ <li><tt><em>collection</em>.empty?</tt></li>
994
+ <li><tt><em>collection</em>.size</tt></li>
995
+ <li><tt><em>collection</em>.find(&#8230;)</tt></li>
996
+ <li><tt><em>collection</em>.where(&#8230;)</tt></li>
997
+ <li><tt><em>collection</em>.exists?(&#8230;)</tt></li>
998
+ <li><tt><em>collection</em>.build(attributes = {}, &#8230;)</tt></li>
999
+ <li><tt><em>collection</em>.create(attributes = {})</tt></li>
1000
+ </ul>
1001
+ <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>
1002
+ <div class="code_container">
1003
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1004
+ class Customer &lt; ActiveRecord::Base
1005
+ has_many :orders
1006
+ end
1007
+ </pre>
1008
+ </div>
1009
+ <p>Each instance of the customer model will have these methods:</p>
1010
+ <div class="code_container">
1011
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1012
+ orders(force_reload = false)
1013
+ orders&lt;&lt;(object, ...)
1014
+ orders.delete(object, ...)
1015
+ orders=objects
1016
+ order_ids
1017
+ order_ids=ids
1018
+ orders.clear
1019
+ orders.empty?
1020
+ orders.size
1021
+ orders.find(...)
1022
+ orders.where(...)
1023
+ orders.exists?(...)
1024
+ orders.build(attributes = {}, ...)
1025
+ orders.create(attributes = {})
1026
+ </pre>
1027
+ </div>
1028
+ <h6 id="has_many-collection">4.3.1.1 <tt><em>collection</em>(force_reload = false)</tt></h6>
1029
+ <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>
1030
+ <div class="code_container">
1031
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1032
+ @orders = @customer.orders
1033
+ </pre>
1034
+ </div>
1035
+ <h6 id="has_many-collection-lt_lt">4.3.1.2 <tt><em>collection</em>&lt;&lt;(object, &#8230;)</tt></h6>
1036
+ <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>
1037
+ <div class="code_container">
1038
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1039
+ @customer.orders &lt;&lt; @order1
1040
+ </pre>
1041
+ </div>
1042
+ <h6 id="has_many-collection-delete">4.3.1.3 <tt><em>collection</em>.delete(object, &#8230;)</tt></h6>
1043
+ <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>
1044
+ <div class="code_container">
1045
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1046
+ @customer.orders.delete(@order1)
1047
+ </pre>
1048
+ </div>
1049
+ <div class="warning"><p>Additionally, objects will be destroyed if they&#8217;re associated with <tt>:dependent => :destroy</tt>, and deleted if they&#8217;re associated with <tt>:dependent => :delete_all</tt>.</p></div>
1050
+ <h6 id="has_many-collection-equal">4.3.1.4 <tt><em>collection</em>=objects</tt></h6>
1051
+ <p>The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.</p>
1052
+ <h6 id="has_many-collection_singular">4.3.1.5 <tt><em>collection_singular</em>_ids</tt></h6>
1053
+ <p>The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.</p>
1054
+ <div class="code_container">
1055
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1056
+ @order_ids = @customer.order_ids
1057
+ </pre>
1058
+ </div>
1059
+ <h6 id="has_many-collection_singular_ids_ids">4.3.1.6 <tt><em>collection_singular</em>_ids=ids</tt></h6>
1060
+ <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>
1061
+ <h6 id="has_many-collection-clear">4.3.1.7 <tt><em>collection</em>.clear</tt></h6>
1062
+ <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 => :destroy</tt>, deletes them directly from the database if <tt>:dependent => :delete_all</tt>, and otherwise sets their foreign keys to <tt>NULL</tt>.</p>
1063
+ <h6 id="has_many-collection-empty">4.3.1.8 <tt><em>collection</em>.empty?</tt></h6>
1064
+ <p>The <tt><em>collection</em>.empty?</tt> method returns <tt>true</tt> if the collection does not contain any associated objects.</p>
1065
+ <div class="code_container">
1066
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1067
+ &lt;% if @customer.orders.empty? %&gt;
1068
+ No Orders Found
1069
+ &lt;% end %&gt;
1070
+ </pre>
1071
+ </div>
1072
+ <h6 id="has_many-collection-size">4.3.1.9 <tt><em>collection</em>.size</tt></h6>
1073
+ <p>The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.</p>
1074
+ <div class="code_container">
1075
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1076
+ @order_count = @customer.orders.size
1077
+ </pre>
1078
+ </div>
1079
+ <h6 id="has_many-collection-find">4.3.1.10 <tt><em>collection</em>.find(&#8230;)</tt></h6>
1080
+ <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>
1081
+ <div class="code_container">
1082
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1083
+ @open_orders = @customer.orders.where(:open =&gt; 1)
1084
+ </pre>
1085
+ </div>
1086
+ <h6 id="has_many-collection-where">4.3.1.11 <tt><em>collection</em>.where(&#8230;)</tt></h6>
1087
+ <p>The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.</p>
1088
+ <div class="code_container">
1089
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1090
+ @open_orders = @customer.orders.where(:open =&gt; true) # No query yet
1091
+ @open_order = @open_orders.first # Now the database will be queried
1092
+ </pre>
1093
+ </div>
1094
+ <h6 id="has_many-collection-exists">4.3.1.12 <tt><em>collection</em>.exists?(&#8230;)</tt></h6>
1095
+ <p>The <tt><em>collection</em>.exists?</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>
1096
+ <h6 id="has_many-collection-build">4.3.1.13 <tt><em>collection</em>.build(attributes = {}, &#8230;)</tt></h6>
1097
+ <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>
1098
+ <div class="code_container">
1099
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1100
+ @order = @customer.orders.build(:order_date =&gt; Time.now,
1101
+ :order_number =&gt; &quot;A12345&quot;)
1102
+ </pre>
1103
+ </div>
1104
+ <h6 id="has_many-collection-create">4.3.1.14 <tt><em>collection</em>.create(attributes = {})</tt></h6>
1105
+ <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, once it passes all of the validations specified on the associated model, the associated object <em>will</em> be saved.</p>
1106
+ <div class="code_container">
1107
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1108
+ @order = @customer.orders.create(:order_date =&gt; Time.now,
1109
+ :order_number =&gt; &quot;A12345&quot;)
1110
+ </pre>
1111
+ </div>
1112
+ <h5 id="options-for-has_many">4.3.2 Options for <tt>has_many</tt></h5>
1113
+ <p>While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the <tt>has_many</tt> association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:</p>
1114
+ <div class="code_container">
1115
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1116
+ class Customer &lt; ActiveRecord::Base
1117
+ has_many :orders, :dependent =&gt; :delete_all, :validate =&gt; :false
1118
+ end
1119
+ </pre>
1120
+ </div>
1121
+ <p>The <tt>has_many</tt> association supports these options:</p>
1122
+ <ul>
1123
+ <li><tt>:as</tt></li>
1124
+ <li><tt>:autosave</tt></li>
1125
+ <li><tt>:class_name</tt></li>
1126
+ <li><tt>:conditions</tt></li>
1127
+ <li><tt>:counter_sql</tt></li>
1128
+ <li><tt>:dependent</tt></li>
1129
+ <li><tt>:extend</tt></li>
1130
+ <li><tt>:finder_sql</tt></li>
1131
+ <li><tt>:foreign_key</tt></li>
1132
+ <li><tt>:group</tt></li>
1133
+ <li><tt>:include</tt></li>
1134
+ <li><tt>:limit</tt></li>
1135
+ <li><tt>:offset</tt></li>
1136
+ <li><tt>:order</tt></li>
1137
+ <li><tt>:primary_key</tt></li>
1138
+ <li><tt>:readonly</tt></li>
1139
+ <li><tt>:select</tt></li>
1140
+ <li><tt>:source</tt></li>
1141
+ <li><tt>:source_type</tt></li>
1142
+ <li><tt>:through</tt></li>
1143
+ <li><tt>:uniq</tt></li>
1144
+ <li><tt>:validate</tt></li>
1145
+ </ul>
1146
+ <h6 id="has_many-as">4.3.2.1 <tt>:as</tt></h6>
1147
+ <p>Setting the <tt>:as</tt> option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>.</p>
1148
+ <h6 id="has_many-autosave">4.3.2.2 <tt>:autosave</tt></h6>
1149
+ <p>If you set the <tt>:autosave</tt> option to <tt>true</tt>, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.</p>
1150
+ <h6 id="has_many-class_name">4.3.2.3 <tt>:class_name</tt></h6>
1151
+ <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&#8217;d set things up this way:</p>
1152
+ <div class="code_container">
1153
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1154
+ class Customer &lt; ActiveRecord::Base
1155
+ has_many :orders, :class_name =&gt; &quot;Transaction&quot;
1156
+ end
1157
+ </pre>
1158
+ </div>
1159
+ <h6 id="has_many-conditions">4.3.2.4 <tt>:conditions</tt></h6>
1160
+ <p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by an <span class="caps">SQL</span> <tt>WHERE</tt> clause).</p>
1161
+ <div class="code_container">
1162
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1163
+ class Customer &lt; ActiveRecord::Base
1164
+ has_many :confirmed_orders, :class_name =&gt; &quot;Order&quot;,
1165
+ :conditions =&gt; &quot;confirmed = 1&quot;
1166
+ end
1167
+ </pre>
1168
+ </div>
1169
+ <p>You can also set conditions via a hash:</p>
1170
+ <div class="code_container">
1171
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1172
+ class Customer &lt; ActiveRecord::Base
1173
+ has_many :confirmed_orders, :class_name =&gt; &quot;Order&quot;,
1174
+ :conditions =&gt; { :confirmed =&gt; true }
1175
+ end
1176
+ </pre>
1177
+ </div>
1178
+ <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>
1179
+ <p>If you need to evaluate conditions dynamically at runtime, use a proc:</p>
1180
+ <div class="code_container">
1181
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1182
+ class Customer &lt; ActiveRecord::Base
1183
+ has_many :latest_orders, :class_name =&gt; &quot;Order&quot;,
1184
+ :conditions =&gt; proc { &quot;orders.created_at &gt; #{10.hours.ago.to_s(:db).inspect}&quot; }
1185
+ end
1186
+ </pre>
1187
+ </div>
1188
+ <h6 id="has_many-counter_sql">4.3.2.5 <tt>:counter_sql</tt></h6>
1189
+ <p>Normally Rails automatically generates the proper <span class="caps">SQL</span> to count the association members. With the <tt>:counter_sql</tt> option, you can specify a complete <span class="caps">SQL</span> statement to count them yourself.</p>
1190
+ <div class="note"><p>If you specify <tt>:finder_sql</tt> but not <tt>:counter_sql</tt>, then the counter <span class="caps">SQL</span> will be generated by substituting <tt>SELECT COUNT(*) FROM</tt> for the <tt>SELECT ... FROM</tt> clause of your <tt>:finder_sql</tt> statement.</p></div>
1191
+ <h6 id="has_many-dependent">4.3.2.6 <tt>:dependent</tt></h6>
1192
+ <p>If you set the <tt>:dependent</tt> option to <tt>:destroy</tt>, then deleting this object will call the <tt>destroy</tt> 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>
1193
+ <div class="note"><p>This option is ignored when you use the <tt>:through</tt> option on the association.</p></div>
1194
+ <h6 id="has_many-extend">4.3.2.7 <tt>:extend</tt></h6>
1195
+ <p>The <tt>:extend</tt> option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.</p>
1196
+ <h6 id="has_many-finder_sql">4.3.2.8 <tt>:finder_sql</tt></h6>
1197
+ <p>Normally Rails automatically generates the proper <span class="caps">SQL</span> to fetch the association members. With the <tt>:finder_sql</tt> option, you can specify a complete <span class="caps">SQL</span> statement to fetch them yourself. If fetching objects requires complex multi-table <span class="caps">SQL</span>, this may be necessary.</p>
1198
+ <h6 id="has_many-foreign_key">4.3.2.9 <tt>:foreign_key</tt></h6>
1199
+ <p>By convention, Rails assumes 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>
1200
+ <div class="code_container">
1201
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1202
+ class Customer &lt; ActiveRecord::Base
1203
+ has_many :orders, :foreign_key =&gt; &quot;cust_id&quot;
1204
+ end
1205
+ </pre>
1206
+ </div>
1207
+ <div class="info"><p>In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.</p></div>
1208
+ <h6 id="has_many-group">4.3.2.10 <tt>:group</tt></h6>
1209
+ <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 <span class="caps">SQL</span>.</p>
1210
+ <div class="code_container">
1211
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1212
+ class Customer &lt; ActiveRecord::Base
1213
+ has_many :line_items, :through =&gt; :orders, :group =&gt; &quot;orders.id&quot;
1214
+ end
1215
+ </pre>
1216
+ </div>
1217
+ <h6 id="has_many-include">4.3.2.11 <tt>:include</tt></h6>
1218
+ <p>You can use the <tt>:include</tt> option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p>
1219
+ <div class="code_container">
1220
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1221
+ class Customer &lt; ActiveRecord::Base
1222
+ has_many :orders
1223
+ end
1224
+
1225
+ class Order &lt; ActiveRecord::Base
1226
+ belongs_to :customer
1227
+ has_many :line_items
1228
+ end
1229
+
1230
+ class LineItem &lt; ActiveRecord::Base
1231
+ belongs_to :order
1232
+ end
1233
+ </pre>
1234
+ </div>
1235
+ <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>
1236
+ <div class="code_container">
1237
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1238
+ class Customer &lt; ActiveRecord::Base
1239
+ has_many :orders, :include =&gt; :line_items
1240
+ end
1241
+
1242
+ class Order &lt; ActiveRecord::Base
1243
+ belongs_to :customer
1244
+ has_many :line_items
1245
+ end
1246
+
1247
+ class LineItem &lt; ActiveRecord::Base
1248
+ belongs_to :order
1249
+ end
1250
+ </pre>
1251
+ </div>
1252
+ <h6 id="has_many-limit">4.3.2.12 <tt>:limit</tt></h6>
1253
+ <p>The <tt>:limit</tt> option lets you restrict the total number of objects that will be fetched through an association.</p>
1254
+ <div class="code_container">
1255
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1256
+ class Customer &lt; ActiveRecord::Base
1257
+ has_many :recent_orders, :class_name =&gt; &quot;Order&quot;,
1258
+ :order =&gt; &quot;order_date DESC&quot;, :limit =&gt; 100
1259
+ end
1260
+ </pre>
1261
+ </div>
1262
+ <h6 id="has_many-offset">4.3.2.13 <tt>:offset</tt></h6>
1263
+ <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 => 11</tt>, it will skip the first 11 records.</p>
1264
+ <h6 id="has_many-order">4.3.2.14 <tt>:order</tt></h6>
1265
+ <p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by an <span class="caps">SQL</span> <tt>ORDER BY</tt> clause).</p>
1266
+ <div class="code_container">
1267
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1268
+ class Customer &lt; ActiveRecord::Base
1269
+ has_many :orders, :order =&gt; &quot;date_confirmed DESC&quot;
1270
+ end
1271
+ </pre>
1272
+ </div>
1273
+ <h6 id="has_many-primary_key">4.3.2.15 <tt>:primary_key</tt></h6>
1274
+ <p>By convention, Rails assumes that the column used to hold the primary key of the association is <tt>id</tt>. You can override this and explicitly specify the primary key with the <tt>:primary_key</tt> option.</p>
1275
+ <h6 id="has_many-readonly">4.3.2.16 <tt>:readonly</tt></h6>
1276
+ <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>
1277
+ <h6 id="has_many-select">4.3.2.17 <tt>:select</tt></h6>
1278
+ <p>The <tt>:select</tt> option lets you override the <span class="caps">SQL</span> <tt>SELECT</tt> clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.</p>
1279
+ <div class="warning"><p>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.</p></div>
1280
+ <h6 id="has_many-source">4.3.2.18 <tt>:source</tt></h6>
1281
+ <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>
1282
+ <h6 id="has_many-source_type">4.3.2.19 <tt>:source_type</tt></h6>
1283
+ <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>
1284
+ <h6 id="has_many-through">4.3.2.20 <tt>:through</tt></h6>
1285
+ <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 <a href="#the-has_many-through-association">earlier in this guide</a>.</p>
1286
+ <h6 id="has_many-uniq">4.3.2.21 <tt>:uniq</tt></h6>
1287
+ <p>Set the <tt>:uniq</tt> option to true to keep the collection free of duplicates. This is mostly useful together with the <tt>:through</tt> option.</p>
1288
+ <div class="code_container">
1289
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1290
+ class Person &lt; ActiveRecord::Base
1291
+ has_many :readings
1292
+ has_many :posts, :through =&gt; :readings
1293
+ end
1294
+
1295
+ person = Person.create(:name =&gt; 'john')
1296
+ post = Post.create(:name =&gt; 'a1')
1297
+ person.posts &lt;&lt; post
1298
+ person.posts &lt;&lt; post
1299
+ person.posts.inspect # =&gt; [#&lt;Post id: 5, name: &quot;a1&quot;&gt;, #&lt;Post id: 5, name: &quot;a1&quot;&gt;]
1300
+ Reading.all.inspect # =&gt; [#&lt;Reading id: 12, person_id: 5, post_id: 5&gt;, #&lt;Reading id: 13, person_id: 5, post_id: 5&gt;]
1301
+ </pre>
1302
+ </div>
1303
+ <p>In the above case there are two readings and <tt>person.posts</tt> brings out both of them even though these records are pointing to the same post.</p>
1304
+ <p>Now let&#8217;s set <tt>:uniq</tt> to true:</p>
1305
+ <div class="code_container">
1306
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1307
+ class Person
1308
+ has_many :readings
1309
+ has_many :posts, :through =&gt; :readings, :uniq =&gt; true
1310
+ end
1311
+
1312
+ person = Person.create(:name =&gt; 'honda')
1313
+ post = Post.create(:name =&gt; 'a1')
1314
+ person.posts &lt;&lt; post
1315
+ person.posts &lt;&lt; post
1316
+ person.posts.inspect # =&gt; [#&lt;Post id: 7, name: &quot;a1&quot;&gt;]
1317
+ Reading.all.inspect # =&gt; [#&lt;Reading id: 16, person_id: 7, post_id: 7&gt;, #&lt;Reading id: 17, person_id: 7, post_id: 7&gt;]
1318
+ </pre>
1319
+ </div>
1320
+ <p>In the above case there are still two readings. However <tt>person.posts</tt> shows only one post because the collection loads only unique records.</p>
1321
+ <h6 id="has_many-validate">4.3.2.22 <tt>:validate</tt></h6>
1322
+ <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>
1323
+ <h5 id="has_many-when_are_objects_saved">4.3.3 When are Objects Saved?</h5>
1324
+ <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>
1325
+ <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>
1326
+ <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>
1327
+ <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>
1328
+ <h4 id="has_and_belongs_to_many-association-reference">4.4 <tt>has_and_belongs_to_many</tt> Association Reference</h4>
1329
+ <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>
1330
+ <h5 id="methods-added-by-has_and_belongs_to_many">4.4.1 Methods Added by <tt>has_and_belongs_to_many</tt></h5>
1331
+ <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>
1332
+ <ul>
1333
+ <li><tt><em>collection</em>(force_reload = false)</tt></li>
1334
+ <li><tt><em>collection</em>&lt;&lt;(object, &#8230;)</tt></li>
1335
+ <li><tt><em>collection</em>.delete(object, &#8230;)</tt></li>
1336
+ <li><tt><em>collection</em>=objects</tt></li>
1337
+ <li><tt><em>collection_singular</em>_ids</tt></li>
1338
+ <li><tt><em>collection_singular</em>_ids=ids</tt></li>
1339
+ <li><tt><em>collection</em>.clear</tt></li>
1340
+ <li><tt><em>collection</em>.empty?</tt></li>
1341
+ <li><tt><em>collection</em>.size</tt></li>
1342
+ <li><tt><em>collection</em>.find(&#8230;)</tt></li>
1343
+ <li><tt><em>collection</em>.where(&#8230;)</tt></li>
1344
+ <li><tt><em>collection</em>.exists?(&#8230;)</tt></li>
1345
+ <li><tt><em>collection</em>.build(attributes = {})</tt></li>
1346
+ <li><tt><em>collection</em>.create(attributes = {})</tt></li>
1347
+ </ul>
1348
+ <p>In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to <tt>has_and_belongs_to_many</tt>, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol. For example, given the declaration:</p>
1349
+ <div class="code_container">
1350
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1351
+ class Part &lt; ActiveRecord::Base
1352
+ has_and_belongs_to_many :assemblies
1353
+ end
1354
+ </pre>
1355
+ </div>
1356
+ <p>Each instance of the part model will have these methods:</p>
1357
+ <div class="code_container">
1358
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1359
+ assemblies(force_reload = false)
1360
+ assemblies&lt;&lt;(object, ...)
1361
+ assemblies.delete(object, ...)
1362
+ assemblies=objects
1363
+ assembly_ids
1364
+ assembly_ids=ids
1365
+ assemblies.clear
1366
+ assemblies.empty?
1367
+ assemblies.size
1368
+ assemblies.find(...)
1369
+ assemblies.where(...)
1370
+ assemblies.exists?(...)
1371
+ assemblies.build(attributes = {}, ...)
1372
+ assemblies.create(attributes = {})
1373
+ </pre>
1374
+ </div>
1375
+ <h6 id="additional-column-methods">4.4.1.1 Additional Column Methods</h6>
1376
+ <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>
1377
+ <div class="warning"><p>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>.</p></div>
1378
+ <h6 id="has_and_belongs_to_many-collection">4.4.1.2 <tt><em>collection</em>(force_reload = false)</tt></h6>
1379
+ <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>
1380
+ <div class="code_container">
1381
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1382
+ @assemblies = @part.assemblies
1383
+ </pre>
1384
+ </div>
1385
+ <h6 id="has_and_belongs_to_many-collection-lt_lt">4.4.1.3 <tt><em>collection</em>&lt;&lt;(object, &#8230;)</tt></h6>
1386
+ <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>
1387
+ <div class="code_container">
1388
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1389
+ @part.assemblies &lt;&lt; @assembly1
1390
+ </pre>
1391
+ </div>
1392
+ <div class="note"><p>This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>.</p></div>
1393
+ <h6 id="has_and_belongs_to_many-collection-delete">4.4.1.4 <tt><em>collection</em>.delete(object, &#8230;)</tt></h6>
1394
+ <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>
1395
+ <div class="code_container">
1396
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1397
+ @part.assemblies.delete(@assembly1)
1398
+ </pre>
1399
+ </div>
1400
+ <h6 id="has_and_belongs_to_many-collection-equal">4.4.1.5 <tt><em>collection</em>=objects</tt></h6>
1401
+ <p>The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.</p>
1402
+ <h6 id="has_and_belongs_to_many-collection_singular">4.4.1.6 <tt><em>collection_singular</em>_ids</tt></h6>
1403
+ <p>The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.</p>
1404
+ <div class="code_container">
1405
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1406
+ @assembly_ids = @part.assembly_ids
1407
+ </pre>
1408
+ </div>
1409
+ <h6 id="has_and_belongs_to_many-collection_singular_ids_ids">4.4.1.7 <tt><em>collection_singular</em>_ids=ids</tt></h6>
1410
+ <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>
1411
+ <h6 id="has_and_belongs_to_many-collection-clear">4.4.1.8 <tt><em>collection</em>.clear</tt></h6>
1412
+ <p>The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.</p>
1413
+ <h6 id="has_and_belongs_to_many-collection-empty">4.4.1.9 <tt><em>collection</em>.empty?</tt></h6>
1414
+ <p>The <tt><em>collection</em>.empty?</tt> method returns <tt>true</tt> if the collection does not contain any associated objects.</p>
1415
+ <div class="code_container">
1416
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1417
+ &lt;% if @part.assemblies.empty? %&gt;
1418
+ This part is not used in any assemblies
1419
+ &lt;% end %&gt;
1420
+ </pre>
1421
+ </div>
1422
+ <h6 id="has_and_belongs_to_many-collection-size">4.4.1.10 <tt><em>collection</em>.size</tt></h6>
1423
+ <p>The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.</p>
1424
+ <div class="code_container">
1425
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1426
+ @assembly_count = @part.assemblies.size
1427
+ </pre>
1428
+ </div>
1429
+ <h6 id="has_and_belongs_to_many-collection-find">4.4.1.11 <tt><em>collection</em>.find(&#8230;)</tt></h6>
1430
+ <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>
1431
+ <div class="code_container">
1432
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1433
+ @new_assemblies = @part.assemblies.all(
1434
+ :conditions =&gt; [&quot;created_at &gt; ?&quot;, 2.days.ago])
1435
+ </pre>
1436
+ </div>
1437
+ <div class="note"><p>Beginning with Rails 3, supplying options to the <tt>ActiveRecord::Base.find</tt> method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions.</p></div>
1438
+ <h6 id="has_and_belongs_to_many-collection-where">4.4.1.12 <tt><em>collection</em>.where(&#8230;)</tt></h6>
1439
+ <p>The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection.</p>
1440
+ <div class="code_container">
1441
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1442
+ @new_assemblies = @part.assemblies.where(&quot;created_at &gt; ?&quot;, 2.days.ago)
1443
+ </pre>
1444
+ </div>
1445
+ <h6 id="has_and_belongs_to_many-collection-exists">4.4.1.13 <tt><em>collection</em>.exists?(&#8230;)</tt></h6>
1446
+ <p>The <tt><em>collection</em>.exists?</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>
1447
+ <h6 id="has_and_belongs_to_many-collection-build">4.4.1.14 <tt><em>collection</em>.build(attributes = {})</tt></h6>
1448
+ <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>
1449
+ <div class="code_container">
1450
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1451
+ @assembly = @part.assemblies.build(
1452
+ {:assembly_name =&gt; &quot;Transmission housing&quot;})
1453
+ </pre>
1454
+ </div>
1455
+ <h6 id="has_and_belongs_to_many-create-attributes">4.4.1.15 <tt><em>collection</em>.create(attributes = {})</tt></h6>
1456
+ <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 the join table will be created, and, once it passes all of the validations specified on the associated model, the associated object <em>will</em> be saved.</p>
1457
+ <div class="code_container">
1458
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1459
+ @assembly = @part.assemblies.create(
1460
+ {:assembly_name =&gt; &quot;Transmission housing&quot;})
1461
+ </pre>
1462
+ </div>
1463
+ <h5 id="options-for-has_and_belongs_to_many">4.4.2 Options for <tt>has_and_belongs_to_many</tt></h5>
1464
+ <p>While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the <tt>has_and_belongs_to_many</tt> association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:</p>
1465
+ <div class="code_container">
1466
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1467
+ class Parts &lt; ActiveRecord::Base
1468
+ has_and_belongs_to_many :assemblies, :uniq =&gt; true,
1469
+ :read_only =&gt; true
1470
+ end
1471
+ </pre>
1472
+ </div>
1473
+ <p>The <tt>has_and_belongs_to_many</tt> association supports these options:</p>
1474
+ <ul>
1475
+ <li><tt>:association_foreign_key</tt></li>
1476
+ <li><tt>:autosave</tt></li>
1477
+ <li><tt>:class_name</tt></li>
1478
+ <li><tt>:conditions</tt></li>
1479
+ <li><tt>:counter_sql</tt></li>
1480
+ <li><tt>:delete_sql</tt></li>
1481
+ <li><tt>:extend</tt></li>
1482
+ <li><tt>:finder_sql</tt></li>
1483
+ <li><tt>:foreign_key</tt></li>
1484
+ <li><tt>:group</tt></li>
1485
+ <li><tt>:include</tt></li>
1486
+ <li><tt>:insert_sql</tt></li>
1487
+ <li><tt>:join_table</tt></li>
1488
+ <li><tt>:limit</tt></li>
1489
+ <li><tt>:offset</tt></li>
1490
+ <li><tt>:order</tt></li>
1491
+ <li><tt>:readonly</tt></li>
1492
+ <li><tt>:select</tt></li>
1493
+ <li><tt>:uniq</tt></li>
1494
+ <li><tt>:validate</tt></li>
1495
+ </ul>
1496
+ <h6 id="has_and_belongs_to_many-association_foreign_key">4.4.2.1 <tt>:association_foreign_key</tt></h6>
1497
+ <p>By convention, Rails assumes that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix <tt>_id</tt> added. The <tt>:association_foreign_key</tt> option lets you set the name of the foreign key directly:</p>
1498
+ <div class="info"><p>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:</p></div>
1499
+ <div class="code_container">
1500
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1501
+ class User &lt; ActiveRecord::Base
1502
+ has_and_belongs_to_many :friends, :class_name =&gt; &quot;User&quot;,
1503
+ :foreign_key =&gt; &quot;this_user_id&quot;,
1504
+ :association_foreign_key =&gt; &quot;other_user_id&quot;
1505
+ end
1506
+ </pre>
1507
+ </div>
1508
+ <h6 id="has_and_belongs_to_many-autosave">4.4.2.2 <tt>:autosave</tt></h6>
1509
+ <p>If you set the <tt>:autosave</tt> option to <tt>true</tt>, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.</p>
1510
+ <h6 id="has_and_belongs_to_many-class_name">4.4.2.3 <tt>:class_name</tt></h6>
1511
+ <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&#8217;d set things up this way:</p>
1512
+ <div class="code_container">
1513
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1514
+ class Parts &lt; ActiveRecord::Base
1515
+ has_and_belongs_to_many :assemblies, :class_name =&gt; &quot;Gadget&quot;
1516
+ end
1517
+ </pre>
1518
+ </div>
1519
+ <h6 id="has_and_belongs_to_many-conditions">4.4.2.4 <tt>:conditions</tt></h6>
1520
+ <p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by an <span class="caps">SQL</span> <tt>WHERE</tt> clause).</p>
1521
+ <div class="code_container">
1522
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1523
+ class Parts &lt; ActiveRecord::Base
1524
+ has_and_belongs_to_many :assemblies,
1525
+ :conditions =&gt; &quot;factory = 'Seattle'&quot;
1526
+ end
1527
+ </pre>
1528
+ </div>
1529
+ <p>You can also set conditions via a hash:</p>
1530
+ <div class="code_container">
1531
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1532
+ class Parts &lt; ActiveRecord::Base
1533
+ has_and_belongs_to_many :assemblies,
1534
+ :conditions =&gt; { :factory =&gt; 'Seattle' }
1535
+ end
1536
+ </pre>
1537
+ </div>
1538
+ <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 <tt>factory</tt> column has the value &#8220;Seattle&#8221;.</p>
1539
+ <h6 id="has_and_belongs_to_many-counter_sql">4.4.2.5 <tt>:counter_sql</tt></h6>
1540
+ <p>Normally Rails automatically generates the proper <span class="caps">SQL</span> to count the association members. With the <tt>:counter_sql</tt> option, you can specify a complete <span class="caps">SQL</span> statement to count them yourself.</p>
1541
+ <div class="note"><p>If you specify <tt>:finder_sql</tt> but not <tt>:counter_sql</tt>, then the counter <span class="caps">SQL</span> will be generated by substituting <tt>SELECT COUNT(*) FROM</tt> for the <tt>SELECT ... FROM</tt> clause of your <tt>:finder_sql</tt> statement.</p></div>
1542
+ <h6 id="has_and_belongs_to_many-delete_sql">4.4.2.6 <tt>:delete_sql</tt></h6>
1543
+ <p>Normally Rails automatically generates the proper <span class="caps">SQL</span> to remove links between the associated classes. With the <tt>:delete_sql</tt> option, you can specify a complete <span class="caps">SQL</span> statement to delete them yourself.</p>
1544
+ <h6 id="has_and_belongs_to_many-extend">4.4.2.7 <tt>:extend</tt></h6>
1545
+ <p>The <tt>:extend</tt> option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.</p>
1546
+ <h6 id="has_and_belongs_to_many-finder_sql">4.4.2.8 <tt>:finder_sql</tt></h6>
1547
+ <p>Normally Rails automatically generates the proper <span class="caps">SQL</span> to fetch the association members. With the <tt>:finder_sql</tt> option, you can specify a complete <span class="caps">SQL</span> statement to fetch them yourself. If fetching objects requires complex multi-table <span class="caps">SQL</span>, this may be necessary.</p>
1548
+ <h6 id="has_and_belongs_to_many-foreign_key">4.4.2.9 <tt>:foreign_key</tt></h6>
1549
+ <p>By convention, Rails assumes 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>
1550
+ <div class="code_container">
1551
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1552
+ class User &lt; ActiveRecord::Base
1553
+ has_and_belongs_to_many :friends, :class_name =&gt; &quot;User&quot;,
1554
+ :foreign_key =&gt; &quot;this_user_id&quot;,
1555
+ :association_foreign_key =&gt; &quot;other_user_id&quot;
1556
+ end
1557
+ </pre>
1558
+ </div>
1559
+ <h6 id="has_and_belongs_to_many-group">4.4.2.10 <tt>:group</tt></h6>
1560
+ <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 <span class="caps">SQL</span>.</p>
1561
+ <div class="code_container">
1562
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1563
+ class Parts &lt; ActiveRecord::Base
1564
+ has_and_belongs_to_many :assemblies, :group =&gt; &quot;factory&quot;
1565
+ end
1566
+ </pre>
1567
+ </div>
1568
+ <h6 id="has_and_belongs_to_many-include">4.4.2.11 <tt>:include</tt></h6>
1569
+ <p>You can use the <tt>:include</tt> option to specify second-order associations that should be eager-loaded when this association is used.</p>
1570
+ <h6 id="has_and_belongs_to_many-insert_sql">4.4.2.12 <tt>:insert_sql</tt></h6>
1571
+ <p>Normally Rails automatically generates the proper <span class="caps">SQL</span> to create links between the associated classes. With the <tt>:insert_sql</tt> option, you can specify a complete <span class="caps">SQL</span> statement to insert them yourself.</p>
1572
+ <h6 id="has_and_belongs_to_many-join_table">4.4.2.13 <tt>:join_table</tt></h6>
1573
+ <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>
1574
+ <h6 id="has_and_belongs_to_many-limit">4.4.2.14 <tt>:limit</tt></h6>
1575
+ <p>The <tt>:limit</tt> option lets you restrict the total number of objects that will be fetched through an association.</p>
1576
+ <div class="code_container">
1577
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1578
+ class Parts &lt; ActiveRecord::Base
1579
+ has_and_belongs_to_many :assemblies, :order =&gt; &quot;created_at DESC&quot;,
1580
+ :limit =&gt; 50
1581
+ end
1582
+ </pre>
1583
+ </div>
1584
+ <h6 id="has_and_belongs_to_many-offset">4.4.2.15 <tt>:offset</tt></h6>
1585
+ <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 => 11</tt>, it will skip the first 11 records.</p>
1586
+ <h6 id="has_and_belongs_to_many-order">4.4.2.16 <tt>:order</tt></h6>
1587
+ <p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by an <span class="caps">SQL</span> <tt>ORDER BY</tt> clause).</p>
1588
+ <div class="code_container">
1589
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1590
+ class Parts &lt; ActiveRecord::Base
1591
+ has_and_belongs_to_many :assemblies, :order =&gt; &quot;assembly_name ASC&quot;
1592
+ end
1593
+ </pre>
1594
+ </div>
1595
+ <h6 id="has_and_belongs_to_many-readonly">4.4.2.17 <tt>:readonly</tt></h6>
1596
+ <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>
1597
+ <h6 id="has_and_belongs_to_many-select">4.4.2.18 <tt>:select</tt></h6>
1598
+ <p>The <tt>:select</tt> option lets you override the <span class="caps">SQL</span> <tt>SELECT</tt> clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.</p>
1599
+ <h6 id="has_and_belongs_to_many-uniq">4.4.2.19 <tt>:uniq</tt></h6>
1600
+ <p>Specify the <tt>:uniq => true</tt> option to remove duplicates from the collection.</p>
1601
+ <h6 id="has_and_belongs_to_many-validate">4.4.2.20 <tt>:validate</tt></h6>
1602
+ <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>
1603
+ <h5 id="has_and_belongs_to_many-when_are_objects_saved">4.4.3 When are Objects Saved?</h5>
1604
+ <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>
1605
+ <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>
1606
+ <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>
1607
+ <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>
1608
+ <h4 id="association-callbacks">4.5 Association Callbacks</h4>
1609
+ <p>Normal callbacks hook into the life cycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a <tt>:before_save</tt> callback to cause something to happen just before an object is saved.</p>
1610
+ <p>Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection. There are four available association callbacks:</p>
1611
+ <ul>
1612
+ <li><tt>before_add</tt></li>
1613
+ <li><tt>after_add</tt></li>
1614
+ <li><tt>before_remove</tt></li>
1615
+ <li><tt>after_remove</tt></li>
1616
+ </ul>
1617
+ <p>You define association callbacks by adding options to the association declaration. For example:</p>
1618
+ <div class="code_container">
1619
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1620
+ class Customer &lt; ActiveRecord::Base
1621
+ has_many :orders, :before_add =&gt; :check_credit_limit
1622
+
1623
+ def check_credit_limit(order)
1624
+ ...
1625
+ end
1626
+ end
1627
+ </pre>
1628
+ </div>
1629
+ <p>Rails passes the object being added or removed to the callback.</p>
1630
+ <p>You can stack callbacks on a single event by passing them as an array:</p>
1631
+ <div class="code_container">
1632
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1633
+ class Customer &lt; ActiveRecord::Base
1634
+ has_many :orders,
1635
+ :before_add =&gt; [:check_credit_limit, :calculate_shipping_charges]
1636
+
1637
+ def check_credit_limit(order)
1638
+ ...
1639
+ end
1640
+
1641
+ def calculate_shipping_charges(order)
1642
+ ...
1643
+ end
1644
+ end
1645
+ </pre>
1646
+ </div>
1647
+ <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>
1648
+ <h4 id="association-extensions">4.6 Association Extensions</h4>
1649
+ <p>You&#8217;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>
1650
+ <div class="code_container">
1651
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1652
+ class Customer &lt; ActiveRecord::Base
1653
+ has_many :orders do
1654
+ def find_by_order_prefix(order_number)
1655
+ find_by_region_id(order_number[0..2])
1656
+ end
1657
+ end
1658
+ end
1659
+ </pre>
1660
+ </div>
1661
+ <p>If you have an extension that should be shared by many associations, you can use a named extension module. For example:</p>
1662
+ <div class="code_container">
1663
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1664
+ module FindRecentExtension
1665
+ def find_recent
1666
+ where(&quot;created_at &gt; ?&quot;, 5.days.ago)
1667
+ end
1668
+ end
1669
+
1670
+ class Customer &lt; ActiveRecord::Base
1671
+ has_many :orders, :extend =&gt; FindRecentExtension
1672
+ end
1673
+
1674
+ class Supplier &lt; ActiveRecord::Base
1675
+ has_many :deliveries, :extend =&gt; FindRecentExtension
1676
+ end
1677
+ </pre>
1678
+ </div>
1679
+ <p>To include more than one extension module in a single association, specify an array of modules:</p>
1680
+ <div class="code_container">
1681
+ <pre class="brush: ruby; gutter: false; toolbar: false">
1682
+ class Customer &lt; ActiveRecord::Base
1683
+ has_many :orders,
1684
+ :extend =&gt; [FindRecentExtension, FindActiveExtension]
1685
+ end
1686
+ </pre>
1687
+ </div>
1688
+ <p>Extensions can refer to the internals of the association proxy using these three attributes of the <tt>proxy_association</tt> accessor:</p>
1689
+ <ul>
1690
+ <li><tt>proxy_association.owner</tt> returns the object that the association is a part of.</li>
1691
+ <li><tt>proxy_association.reflection</tt> returns the reflection object that describes the association.</li>
1692
+ <li><tt>proxy_association.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>.</li>
1693
+ </ul>
1694
+
1695
+ <h3>Feedback</h3>
1696
+ <p>
1697
+ You're encouraged to help improve the quality of this guide.
1698
+ </p>
1699
+ <p>
1700
+ If you see any typos or factual errors you are confident to
1701
+ patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
1702
+ and push the change yourself. That branch of Rails has public write access.
1703
+ Commits are still reviewed, but that happens after you've submitted your
1704
+ contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
1705
+ cross-merged with master periodically.
1706
+ </p>
1707
+ <p>
1708
+ You may also find incomplete content, or stuff that is not up to date.
1709
+ Please do add any missing documentation for master. Check the
1710
+ <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
1711
+ for style and conventions.
1712
+ </p>
1713
+ <p>
1714
+ If for whatever reason you spot something to fix but cannot patch it yourself, please
1715
+ <a href="https://github.com/rails/rails/issues">open an issue</a>.
1716
+ </p>
1717
+ <p>And last but not least, any kind of discussion regarding Ruby on Rails
1718
+ documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
1719
+ </p>
1720
+ </div>
1721
+ </div>
1722
+ </div>
1723
+
1724
+ <hr class="hide" />
1725
+ <div id="footer">
1726
+ <div class="wrapper">
1727
+ <p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
1728
+ <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
1729
+ </div>
1730
+ </div>
1731
+
1732
+ <script type="text/javascript" src="javascripts/guides.js"></script>
1733
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
1734
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
1735
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
1736
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
1737
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
1738
+ <script type="text/javascript">
1739
+ SyntaxHighlighter.all()
1740
+ </script>
1741
+ </body>
1742
+ </html>