rails 4.2.0.beta4 → 4.2.0.rc1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (230) hide show
  1. checksums.yaml +4 -4
  2. data/guides/Rakefile +3 -1
  3. data/guides/bug_report_templates/action_controller_gem.rb +2 -2
  4. data/guides/bug_report_templates/action_controller_master.rb +2 -2
  5. data/guides/source/3_0_release_notes.md +2 -2
  6. data/guides/source/4_1_release_notes.md +1 -1
  7. data/guides/source/4_2_release_notes.md +250 -225
  8. data/guides/source/_welcome.html.erb +1 -1
  9. data/guides/source/action_controller_overview.md +6 -6
  10. data/guides/source/action_mailer_basics.md +26 -11
  11. data/guides/source/action_view_overview.md +0 -1
  12. data/guides/source/active_job_basics.md +29 -23
  13. data/guides/source/active_record_postgresql.md +2 -7
  14. data/guides/source/active_record_validations.md +1 -0
  15. data/guides/source/active_support_core_extensions.md +1 -1
  16. data/guides/source/active_support_instrumentation.md +5 -5
  17. data/guides/source/asset_pipeline.md +2 -2
  18. data/guides/source/association_basics.md +0 -2
  19. data/guides/source/command_line.md +6 -15
  20. data/guides/source/configuring.md +4 -4
  21. data/guides/source/documents.yaml +0 -1
  22. data/guides/source/engines.md +26 -15
  23. data/guides/source/form_helpers.md +10 -2
  24. data/guides/source/getting_started.md +9 -9
  25. data/guides/source/rails_on_rack.md +2 -2
  26. data/guides/source/ruby_on_rails_guides_guidelines.md +1 -0
  27. data/guides/source/security.md +1 -1
  28. data/guides/source/testing.md +80 -13
  29. data/guides/source/upgrading_ruby_on_rails.md +23 -20
  30. metadata +29 -229
  31. data/guides/output/2_2_release_notes.html +0 -724
  32. data/guides/output/2_3_release_notes.html +0 -870
  33. data/guides/output/3_0_release_notes.html +0 -773
  34. data/guides/output/3_1_release_notes.html +0 -740
  35. data/guides/output/3_2_release_notes.html +0 -797
  36. data/guides/output/4_0_release_notes.html +0 -523
  37. data/guides/output/4_1_release_notes.html +0 -806
  38. data/guides/output/4_2_release_notes.html +0 -728
  39. data/guides/output/Gemfile +0 -6
  40. data/guides/output/_license.html +0 -226
  41. data/guides/output/_welcome.html +0 -233
  42. data/guides/output/action_controller_overview.html +0 -1335
  43. data/guides/output/action_mailer_basics.html +0 -928
  44. data/guides/output/action_view_overview.html +0 -1509
  45. data/guides/output/active_job_basics.html +0 -546
  46. data/guides/output/active_model_basics.html +0 -438
  47. data/guides/output/active_record_basics.html +0 -594
  48. data/guides/output/active_record_callbacks.html +0 -592
  49. data/guides/output/active_record_migrations.html +0 -1123
  50. data/guides/output/active_record_postgresql.html +0 -675
  51. data/guides/output/active_record_querying.html +0 -1796
  52. data/guides/output/active_record_validations.html +0 -1301
  53. data/guides/output/active_support_core_extensions.html +0 -3450
  54. data/guides/output/active_support_instrumentation.html +0 -1121
  55. data/guides/output/api_documentation_guidelines.html +0 -498
  56. data/guides/output/asset_pipeline.html +0 -1167
  57. data/guides/output/association_basics.html +0 -2086
  58. data/guides/output/caching_with_rails.html +0 -553
  59. data/guides/output/command_line.html +0 -791
  60. data/guides/output/configuring.html +0 -1055
  61. data/guides/output/contributing_to_ruby_on_rails.html +0 -657
  62. data/guides/output/credits.html +0 -284
  63. data/guides/output/debugging_rails_applications.html +0 -1014
  64. data/guides/output/development_dependencies_install.html +0 -478
  65. data/guides/output/engines.html +0 -1438
  66. data/guides/output/form_helpers.html +0 -1074
  67. data/guides/output/generators.html +0 -838
  68. data/guides/output/getting_started.html +0 -2092
  69. data/guides/output/i18n.html +0 -1198
  70. data/guides/output/images/akshaysurve.jpg +0 -0
  71. data/guides/output/images/belongs_to.png +0 -0
  72. data/guides/output/images/book_icon.gif +0 -0
  73. data/guides/output/images/bullet.gif +0 -0
  74. data/guides/output/images/chapters_icon.gif +0 -0
  75. data/guides/output/images/check_bullet.gif +0 -0
  76. data/guides/output/images/credits_pic_blank.gif +0 -0
  77. data/guides/output/images/csrf.png +0 -0
  78. data/guides/output/images/edge_badge.png +0 -0
  79. data/guides/output/images/favicon.ico +0 -0
  80. data/guides/output/images/feature_tile.gif +0 -0
  81. data/guides/output/images/footer_tile.gif +0 -0
  82. data/guides/output/images/fxn.png +0 -0
  83. data/guides/output/images/getting_started/article_with_comments.png +0 -0
  84. data/guides/output/images/getting_started/challenge.png +0 -0
  85. data/guides/output/images/getting_started/confirm_dialog.png +0 -0
  86. data/guides/output/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  87. data/guides/output/images/getting_started/forbidden_attributes_for_new_post.png +0 -0
  88. data/guides/output/images/getting_started/form_with_errors.png +0 -0
  89. data/guides/output/images/getting_started/index_action_with_edit_link.png +0 -0
  90. data/guides/output/images/getting_started/new_article.png +0 -0
  91. data/guides/output/images/getting_started/new_post.png +0 -0
  92. data/guides/output/images/getting_started/post_with_comments.png +0 -0
  93. data/guides/output/images/getting_started/rails_welcome.png +0 -0
  94. data/guides/output/images/getting_started/routing_error_no_controller.png +0 -0
  95. data/guides/output/images/getting_started/routing_error_no_route_matches.png +0 -0
  96. data/guides/output/images/getting_started/show_action_for_articles.png +0 -0
  97. data/guides/output/images/getting_started/show_action_for_posts.png +0 -0
  98. data/guides/output/images/getting_started/template_is_missing_articles_new.png +0 -0
  99. data/guides/output/images/getting_started/template_is_missing_posts_new.png +0 -0
  100. data/guides/output/images/getting_started/undefined_method_post_path.png +0 -0
  101. data/guides/output/images/getting_started/unknown_action_create_for_articles.png +0 -0
  102. data/guides/output/images/getting_started/unknown_action_create_for_posts.png +0 -0
  103. data/guides/output/images/getting_started/unknown_action_new_for_articles.png +0 -0
  104. data/guides/output/images/getting_started/unknown_action_new_for_posts.png +0 -0
  105. data/guides/output/images/grey_bullet.gif +0 -0
  106. data/guides/output/images/habtm.png +0 -0
  107. data/guides/output/images/has_many.png +0 -0
  108. data/guides/output/images/has_many_through.png +0 -0
  109. data/guides/output/images/has_one.png +0 -0
  110. data/guides/output/images/has_one_through.png +0 -0
  111. data/guides/output/images/header_backdrop.png +0 -0
  112. data/guides/output/images/header_tile.gif +0 -0
  113. data/guides/output/images/i18n/demo_html_safe.png +0 -0
  114. data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
  115. data/guides/output/images/i18n/demo_translated_en.png +0 -0
  116. data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
  117. data/guides/output/images/i18n/demo_translation_missing.png +0 -0
  118. data/guides/output/images/i18n/demo_untranslated.png +0 -0
  119. data/guides/output/images/icons/README +0 -5
  120. data/guides/output/images/icons/callouts/1.png +0 -0
  121. data/guides/output/images/icons/callouts/10.png +0 -0
  122. data/guides/output/images/icons/callouts/11.png +0 -0
  123. data/guides/output/images/icons/callouts/12.png +0 -0
  124. data/guides/output/images/icons/callouts/13.png +0 -0
  125. data/guides/output/images/icons/callouts/14.png +0 -0
  126. data/guides/output/images/icons/callouts/15.png +0 -0
  127. data/guides/output/images/icons/callouts/2.png +0 -0
  128. data/guides/output/images/icons/callouts/3.png +0 -0
  129. data/guides/output/images/icons/callouts/4.png +0 -0
  130. data/guides/output/images/icons/callouts/5.png +0 -0
  131. data/guides/output/images/icons/callouts/6.png +0 -0
  132. data/guides/output/images/icons/callouts/7.png +0 -0
  133. data/guides/output/images/icons/callouts/8.png +0 -0
  134. data/guides/output/images/icons/callouts/9.png +0 -0
  135. data/guides/output/images/icons/caution.png +0 -0
  136. data/guides/output/images/icons/example.png +0 -0
  137. data/guides/output/images/icons/home.png +0 -0
  138. data/guides/output/images/icons/important.png +0 -0
  139. data/guides/output/images/icons/next.png +0 -0
  140. data/guides/output/images/icons/note.png +0 -0
  141. data/guides/output/images/icons/prev.png +0 -0
  142. data/guides/output/images/icons/tip.png +0 -0
  143. data/guides/output/images/icons/up.png +0 -0
  144. data/guides/output/images/icons/warning.png +0 -0
  145. data/guides/output/images/nav_arrow.gif +0 -0
  146. data/guides/output/images/oscardelben.jpg +0 -0
  147. data/guides/output/images/polymorphic.png +0 -0
  148. data/guides/output/images/radar.png +0 -0
  149. data/guides/output/images/rails4_features.png +0 -0
  150. data/guides/output/images/rails_guides_kindle_cover.jpg +0 -0
  151. data/guides/output/images/rails_guides_logo.gif +0 -0
  152. data/guides/output/images/rails_logo_remix.gif +0 -0
  153. data/guides/output/images/session_fixation.png +0 -0
  154. data/guides/output/images/tab_grey.gif +0 -0
  155. data/guides/output/images/tab_info.gif +0 -0
  156. data/guides/output/images/tab_note.gif +0 -0
  157. data/guides/output/images/tab_red.gif +0 -0
  158. data/guides/output/images/tab_yellow.gif +0 -0
  159. data/guides/output/images/tab_yellow.png +0 -0
  160. data/guides/output/images/vijaydev.jpg +0 -0
  161. data/guides/output/index.html +0 -354
  162. data/guides/output/initialization.html +0 -876
  163. data/guides/output/javascripts/guides.js +0 -59
  164. data/guides/output/javascripts/jquery.min.js +0 -4
  165. data/guides/output/javascripts/responsive-tables.js +0 -43
  166. data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  167. data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  168. data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  169. data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  170. data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  171. data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  172. data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  173. data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  174. data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  175. data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  176. data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  177. data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  178. data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  179. data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  180. data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  181. data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  182. data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  183. data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  184. data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  185. data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  186. data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  187. data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  188. data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  189. data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  190. data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  191. data/guides/output/javascripts/syntaxhighlighter/shCore.js +0 -17
  192. data/guides/output/layout.html +0 -448
  193. data/guides/output/layouts_and_rendering.html +0 -1541
  194. data/guides/output/maintenance_policy.html +0 -257
  195. data/guides/output/migrations.html +0 -1360
  196. data/guides/output/nested_model_forms.html +0 -412
  197. data/guides/output/plugins.html +0 -644
  198. data/guides/output/rails_application_templates.html +0 -450
  199. data/guides/output/rails_on_rack.html +0 -547
  200. data/guides/output/routing.html +0 -1631
  201. data/guides/output/ruby_on_rails_guides_guidelines.html +0 -329
  202. data/guides/output/security.html +0 -935
  203. data/guides/output/stylesheets/fixes.css +0 -16
  204. data/guides/output/stylesheets/kindle.css +0 -11
  205. data/guides/output/stylesheets/main.css +0 -713
  206. data/guides/output/stylesheets/print.css +0 -52
  207. data/guides/output/stylesheets/reset.css +0 -43
  208. data/guides/output/stylesheets/responsive-tables.css +0 -50
  209. data/guides/output/stylesheets/style.css +0 -13
  210. data/guides/output/stylesheets/syntaxhighlighter/shCore.css +0 -226
  211. data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  212. data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  213. data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  214. data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  215. data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  216. data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  217. data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  218. data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  219. data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  220. data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  221. data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  222. data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  223. data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  224. data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  225. data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  226. data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  227. data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  228. data/guides/output/testing.html +0 -1350
  229. data/guides/output/upgrading_ruby_on_rails.html +0 -1135
  230. data/guides/output/working_with_javascript_in_rails.html +0 -587
@@ -1,2086 +0,0 @@
1
- <!DOCTYPE html>
2
-
3
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4
- <head>
5
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
6
- <meta name="viewport" content="width=device-width, initial-scale=1"/>
7
-
8
- <title>Active Record Associations — Ruby on Rails Guides</title>
9
- <link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
10
- <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
11
-
12
- <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
13
- <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
14
-
15
- <link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
16
-
17
- <link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
18
- </head>
19
- <body class="guide">
20
- <div id="topNav">
21
- <div class="wrapper">
22
- <strong class="more-info-label">More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
23
- <span class="red-button more-info-button">
24
- More Ruby on Rails
25
- </span>
26
- <ul class="more-info-links s-hidden">
27
- <li class="more-info"><a href="http://rubyonrails.org/">Overview</a></li>
28
- <li class="more-info"><a href="http://rubyonrails.org/download">Download</a></li>
29
- <li class="more-info"><a href="http://rubyonrails.org/deploy">Deploy</a></li>
30
- <li class="more-info"><a href="https://github.com/rails/rails">Code</a></li>
31
- <li class="more-info"><a href="http://rubyonrails.org/screencasts">Screencasts</a></li>
32
- <li class="more-info"><a href="http://rubyonrails.org/documentation">Documentation</a></li>
33
- <li class="more-info"><a href="http://rubyonrails.org/community">Community</a></li>
34
- <li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
35
- </ul>
36
- </div>
37
- </div>
38
- <div id="header">
39
- <div class="wrapper clearfix">
40
- <h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
41
- <ul class="nav">
42
- <li><a class="nav-item" href="index.html">Home</a></li>
43
- <li class="guides-index guides-index-large">
44
- <a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Guides Index</a>
45
- <div id="guides" class="clearfix" style="display: none;">
46
- <hr />
47
- <dl class="L">
48
- <dt>Start Here</dt>
49
- <dd><a href="getting_started.html">Getting Started with Rails</a></dd>
50
- <dt>Models</dt>
51
- <dd><a href="active_record_basics.html">Active Record Basics</a></dd>
52
- <dd><a href="active_record_migrations.html">Active Record Migrations</a></dd>
53
- <dd><a href="active_record_validations.html">Active Record Validations</a></dd>
54
- <dd><a href="active_record_callbacks.html">Active Record Callbacks</a></dd>
55
- <dd><a href="association_basics.html">Active Record Associations</a></dd>
56
- <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
57
- <dt>Views</dt>
58
- <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
59
- <dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
60
- <dt>Controllers</dt>
61
- <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
62
- <dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
63
- </dl>
64
- <dl class="R">
65
- <dt>Digging Deeper</dt>
66
- <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
67
- <dd><a href="i18n.html">Rails Internationalization API</a></dd>
68
- <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
69
- <dd><a href="active_job_basics.html">Active Job Basics</a></dd>
70
- <dd><a href="security.html">Securing Rails Applications</a></dd>
71
- <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
72
- <dd><a href="configuring.html">Configuring Rails Applications</a></dd>
73
- <dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
74
- <dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
75
- <dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
76
- <dt>Extending Rails</dt>
77
- <dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
78
- <dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
79
- <dt>Contributing to Ruby on Rails</dt>
80
- <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
81
- <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
82
- <dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
83
- <dt>Maintenance Policy</dt>
84
- <dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
85
- <dt>Release Notes</dt>
86
- <dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
87
- <dd><a href="4_1_release_notes.html">Ruby on Rails 4.1 Release Notes</a></dd>
88
- <dd><a href="4_0_release_notes.html">Ruby on Rails 4.0 Release Notes</a></dd>
89
- <dd><a href="3_2_release_notes.html">Ruby on Rails 3.2 Release Notes</a></dd>
90
- <dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
91
- <dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
92
- <dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
93
- <dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
94
- </dl>
95
- </div>
96
- </li>
97
- <li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribute</a></li>
98
- <li><a class="nav-item" href="credits.html">Credits</a></li>
99
- <li class="guides-index guides-index-small">
100
- <select class="guides-index-item nav-item">
101
- <option value="index.html">Guides Index</option>
102
- <optgroup label="Start Here">
103
- <option value="getting_started.html">Getting Started with Rails</option>
104
- </optgroup>
105
- <optgroup label="Models">
106
- <option value="active_record_basics.html">Active Record Basics</option>
107
- <option value="active_record_migrations.html">Active Record Migrations</option>
108
- <option value="active_record_validations.html">Active Record Validations</option>
109
- <option value="active_record_callbacks.html">Active Record Callbacks</option>
110
- <option value="association_basics.html">Active Record Associations</option>
111
- <option value="active_record_querying.html">Active Record Query Interface</option>
112
- </optgroup>
113
- <optgroup label="Views">
114
- <option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
115
- <option value="form_helpers.html">Action View Form Helpers</option>
116
- </optgroup>
117
- <optgroup label="Controllers">
118
- <option value="action_controller_overview.html">Action Controller Overview</option>
119
- <option value="routing.html">Rails Routing from the Outside In</option>
120
- </optgroup>
121
- <optgroup label="Digging Deeper">
122
- <option value="active_support_core_extensions.html">Active Support Core Extensions</option>
123
- <option value="i18n.html">Rails Internationalization API</option>
124
- <option value="action_mailer_basics.html">Action Mailer Basics</option>
125
- <option value="active_job_basics.html">Active Job Basics</option>
126
- <option value="security.html">Securing Rails Applications</option>
127
- <option value="debugging_rails_applications.html">Debugging Rails Applications</option>
128
- <option value="configuring.html">Configuring Rails Applications</option>
129
- <option value="command_line.html">Rails Command Line Tools and Rake Tasks</option>
130
- <option value="asset_pipeline.html">Asset Pipeline</option>
131
- <option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
132
- </optgroup>
133
- <optgroup label="Extending Rails">
134
- <option value="rails_on_rack.html">Rails on Rack</option>
135
- <option value="generators.html">Creating and Customizing Rails Generators</option>
136
- </optgroup>
137
- <optgroup label="Contributing to Ruby on Rails">
138
- <option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
139
- <option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
140
- <option value="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</option>
141
- </optgroup>
142
- <optgroup label="Maintenance Policy">
143
- <option value="maintenance_policy.html">Maintenance Policy</option>
144
- </optgroup>
145
- <optgroup label="Release Notes">
146
- <option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
147
- <option value="4_1_release_notes.html">Ruby on Rails 4.1 Release Notes</option>
148
- <option value="4_0_release_notes.html">Ruby on Rails 4.0 Release Notes</option>
149
- <option value="3_2_release_notes.html">Ruby on Rails 3.2 Release Notes</option>
150
- <option value="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</option>
151
- <option value="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</option>
152
- <option value="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</option>
153
- <option value="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</option>
154
- </optgroup>
155
- </select>
156
- </li>
157
- </ul>
158
- </div>
159
- </div>
160
- <hr class="hide" />
161
-
162
- <div id="feature">
163
- <div class="wrapper">
164
- <h2>Active Record Associations</h2><p>This guide covers the association features of Active Record.</p><p>After reading this guide, you will know:</p>
165
- <ul>
166
- <li>How to declare associations between Active Record models.</li>
167
- <li>How to understand the various types of Active Record associations.</li>
168
- <li>How to use the methods added to your models by creating associations.</li>
169
- </ul>
170
-
171
-
172
- <div id="subCol">
173
- <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
174
- <ol class="chapters">
175
- <li><a href="#why-associations-questionmark">Why Associations?</a></li>
176
- <li>
177
- <a href="#the-types-of-associations">The Types of Associations</a>
178
-
179
- <ul>
180
- <li><a href="#the-belongs_to-association">The <code>belongs_to</code> Association</a></li>
181
- <li><a href="#the-has_one-association">The <code>has_one</code> Association</a></li>
182
- <li><a href="#the-has_many-association">The <code>has_many</code> Association</a></li>
183
- <li><a href="#the-has_many-:through-association">The <code>has_many :through</code> Association</a></li>
184
- <li><a href="#the-has_one-:through-association">The <code>has_one :through</code> Association</a></li>
185
- <li><a href="#the-has_and_belongs_to_many-association">The <code>has_and_belongs_to_many</code> Association</a></li>
186
- <li><a href="#choosing-between-belongs_to-and-has_one">Choosing Between <code>belongs_to</code> and <code>has_one</code></a></li>
187
- <li><a href="#choosing-between-has_many-:through-and-has_and_belongs_to_many">Choosing Between <code>has_many :through</code> and <code>has_and_belongs_to_many</code></a></li>
188
- <li><a href="#polymorphic-associations">Polymorphic Associations</a></li>
189
- <li><a href="#self-joins">Self Joins</a></li>
190
- </ul>
191
- </li>
192
- <li>
193
- <a href="#tips,-tricks,-and-warnings">Tips, Tricks, and Warnings</a>
194
-
195
- <ul>
196
- <li><a href="#controlling-caching">Controlling Caching</a></li>
197
- <li><a href="#avoiding-name-collisions">Avoiding Name Collisions</a></li>
198
- <li><a href="#updating-the-schema">Updating the Schema</a></li>
199
- <li><a href="#controlling-association-scope">Controlling Association Scope</a></li>
200
- <li><a href="#bi-directional-associations">Bi-directional Associations</a></li>
201
- </ul>
202
- </li>
203
- <li>
204
- <a href="#detailed-association-reference">Detailed Association Reference</a>
205
-
206
- <ul>
207
- <li><a href="#belongs_to-association-reference"><code>belongs_to</code> Association Reference</a></li>
208
- <li><a href="#has_one-association-reference"><code>has_one</code> Association Reference</a></li>
209
- <li><a href="#has_many-association-reference"><code>has_many</code> Association Reference</a></li>
210
- <li><a href="#has_and_belongs_to_many-association-reference"><code>has_and_belongs_to_many</code> Association Reference</a></li>
211
- <li><a href="#association-callbacks">Association Callbacks</a></li>
212
- <li><a href="#association-extensions">Association Extensions</a></li>
213
- </ul>
214
- </li>
215
- </ol>
216
-
217
- </div>
218
-
219
- </div>
220
- </div>
221
-
222
- <div id="container">
223
- <div class="wrapper">
224
- <div id="mainCol">
225
- <h3 id="why-associations-questionmark">1 Why Associations?</h3><p>Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:</p><div class="code_container">
226
- <pre class="brush: ruby; gutter: false; toolbar: false">
227
- class Customer &lt; ActiveRecord::Base
228
- end
229
-
230
- class Order &lt; ActiveRecord::Base
231
- end
232
-
233
- </pre>
234
- </div>
235
- <p>Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:</p><div class="code_container">
236
- <pre class="brush: ruby; gutter: false; toolbar: false">
237
- @order = Order.create(order_date: Time.now, customer_id: @customer.id)
238
-
239
- </pre>
240
- </div>
241
- <p>Or consider deleting a customer, and ensuring that all of its orders get deleted as well:</p><div class="code_container">
242
- <pre class="brush: ruby; gutter: false; toolbar: false">
243
- @orders = Order.where(customer_id: @customer.id)
244
- @orders.each do |order|
245
- order.destroy
246
- end
247
- @customer.destroy
248
-
249
- </pre>
250
- </div>
251
- <p>With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:</p><div class="code_container">
252
- <pre class="brush: ruby; gutter: false; toolbar: false">
253
- class Customer &lt; ActiveRecord::Base
254
- has_many :orders, dependent: :destroy
255
- end
256
-
257
- class Order &lt; ActiveRecord::Base
258
- belongs_to :customer
259
- end
260
-
261
- </pre>
262
- </div>
263
- <p>With this change, creating a new order for a particular customer is easier:</p><div class="code_container">
264
- <pre class="brush: ruby; gutter: false; toolbar: false">
265
- @order = @customer.orders.create(order_date: Time.now)
266
-
267
- </pre>
268
- </div>
269
- <p>Deleting a customer and all of its orders is <em>much</em> easier:</p><div class="code_container">
270
- <pre class="brush: ruby; gutter: false; toolbar: false">
271
- @customer.destroy
272
-
273
- </pre>
274
- </div>
275
- <p>To learn more about the different types of associations, read the next section of this guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.</p><h3 id="the-types-of-associations">2 The Types of Associations</h3><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 <code>belongs_to</code> 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>
276
- <ul>
277
- <li><code>belongs_to</code></li>
278
- <li><code>has_one</code></li>
279
- <li><code>has_many</code></li>
280
- <li><code>has_many :through</code></li>
281
- <li><code>has_one :through</code></li>
282
- <li><code>has_and_belongs_to_many</code></li>
283
- </ul>
284
- <p>In the remainder of this guide, you'll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.</p><h4 id="the-belongs_to-association">2.1 The <code>belongs_to</code> Association</h4><p>A <code>belongs_to</code> association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way:</p><div class="code_container">
285
- <pre class="brush: ruby; gutter: false; toolbar: false">
286
- class Order &lt; ActiveRecord::Base
287
- belongs_to :customer
288
- end
289
-
290
- </pre>
291
- </div>
292
- <p><img src="images/belongs_to.png" alt="belongs_to Association Diagram"></p><div class="note"><p><code>belongs_to</code> associations <em>must</em> use the singular term. If you used the pluralized form in the above example for the <code>customer</code> association in the <code>Order</code> model, you would be told that there was an "uninitialized constant Order::Customers". This is because Rails automatically infers the class name from the association name. If the association name is wrongly pluralized, then the inferred class will be wrongly pluralized too.</p></div><p>The corresponding migration might look like this:</p><div class="code_container">
293
- <pre class="brush: ruby; gutter: false; toolbar: false">
294
- class CreateOrders &lt; ActiveRecord::Migration
295
- def change
296
- create_table :customers do |t|
297
- t.string :name
298
- t.timestamps
299
- end
300
-
301
- create_table :orders do |t|
302
- t.belongs_to :customer, index: true
303
- t.datetime :order_date
304
- t.timestamps
305
- end
306
- end
307
- end
308
-
309
- </pre>
310
- </div>
311
- <h4 id="the-has_one-association">2.2 The <code>has_one</code> Association</h4><p>A <code>has_one</code> association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:</p><div class="code_container">
312
- <pre class="brush: ruby; gutter: false; toolbar: false">
313
- class Supplier &lt; ActiveRecord::Base
314
- has_one :account
315
- end
316
-
317
- </pre>
318
- </div>
319
- <p><img src="images/has_one.png" alt="has_one Association Diagram"></p><p>The corresponding migration might look like this:</p><div class="code_container">
320
- <pre class="brush: ruby; gutter: false; toolbar: false">
321
- class CreateSuppliers &lt; ActiveRecord::Migration
322
- def change
323
- create_table :suppliers do |t|
324
- t.string :name
325
- t.timestamps
326
- end
327
-
328
- create_table :accounts do |t|
329
- t.belongs_to :supplier, index: true
330
- t.string :account_number
331
- t.timestamps
332
- end
333
- end
334
- end
335
-
336
- </pre>
337
- </div>
338
- <h4 id="the-has_many-association">2.3 The <code>has_many</code> Association</h4><p>A <code>has_many</code> association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a <code>belongs_to</code> association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:</p><div class="code_container">
339
- <pre class="brush: ruby; gutter: false; toolbar: false">
340
- class Customer &lt; ActiveRecord::Base
341
- has_many :orders
342
- end
343
-
344
- </pre>
345
- </div>
346
- <div class="note"><p>The name of the other model is pluralized when declaring a <code>has_many</code> association.</p></div><p><img src="images/has_many.png" alt="has_many Association Diagram"></p><p>The corresponding migration might look like this:</p><div class="code_container">
347
- <pre class="brush: ruby; gutter: false; toolbar: false">
348
- class CreateCustomers &lt; ActiveRecord::Migration
349
- def change
350
- create_table :customers do |t|
351
- t.string :name
352
- t.timestamps
353
- end
354
-
355
- create_table :orders do |t|
356
- t.belongs_to :customer, index:true
357
- t.datetime :order_date
358
- t.timestamps
359
- end
360
- end
361
- end
362
-
363
- </pre>
364
- </div>
365
- <h4 id="the-has_many-:through-association">2.4 The <code>has_many :through</code> Association</h4><p>A <code>has_many :through</code> association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding <em>through</em> a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:</p><div class="code_container">
366
- <pre class="brush: ruby; gutter: false; toolbar: false">
367
- class Physician &lt; ActiveRecord::Base
368
- has_many :appointments
369
- has_many :patients, through: :appointments
370
- end
371
-
372
- class Appointment &lt; ActiveRecord::Base
373
- belongs_to :physician
374
- belongs_to :patient
375
- end
376
-
377
- class Patient &lt; ActiveRecord::Base
378
- has_many :appointments
379
- has_many :physicians, through: :appointments
380
- end
381
-
382
- </pre>
383
- </div>
384
- <p><img src="images/has_many_through.png" alt="has_many :through Association Diagram"></p><p>The corresponding migration might look like this:</p><div class="code_container">
385
- <pre class="brush: ruby; gutter: false; toolbar: false">
386
- class CreateAppointments &lt; ActiveRecord::Migration
387
- def change
388
- create_table :physicians do |t|
389
- t.string :name
390
- t.timestamps
391
- end
392
-
393
- create_table :patients do |t|
394
- t.string :name
395
- t.timestamps
396
- end
397
-
398
- create_table :appointments do |t|
399
- t.belongs_to :physician, index: true
400
- t.belongs_to :patient, index: true
401
- t.datetime :appointment_date
402
- t.timestamps
403
- end
404
- end
405
- end
406
-
407
- </pre>
408
- </div>
409
- <p>The collection of join models can be managed via the API. For example, if you assign</p><div class="code_container">
410
- <pre class="brush: ruby; gutter: false; toolbar: false">
411
- physician.patients = patients
412
-
413
- </pre>
414
- </div>
415
- <p>new join models are created for newly associated objects, and if some are gone their rows are deleted.</p><div class="warning"><p>Automatic deletion of join models is direct, no destroy callbacks are triggered.</p></div><p>The <code>has_many :through</code> association is also useful for setting up "shortcuts" through nested <code>has_many</code> associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:</p><div class="code_container">
416
- <pre class="brush: ruby; gutter: false; toolbar: false">
417
- class Document &lt; ActiveRecord::Base
418
- has_many :sections
419
- has_many :paragraphs, through: :sections
420
- end
421
-
422
- class Section &lt; ActiveRecord::Base
423
- belongs_to :document
424
- has_many :paragraphs
425
- end
426
-
427
- class Paragraph &lt; ActiveRecord::Base
428
- belongs_to :section
429
- end
430
-
431
- </pre>
432
- </div>
433
- <p>With <code>through: :sections</code> specified, Rails will now understand:</p><div class="code_container">
434
- <pre class="brush: ruby; gutter: false; toolbar: false">
435
- @document.paragraphs
436
-
437
- </pre>
438
- </div>
439
- <h4 id="the-has_one-:through-association">2.5 The <code>has_one :through</code> Association</h4><p>A <code>has_one :through</code> association sets up a one-to-one connection with another model. This association indicates
440
- that the declaring model can be matched with one instance of another model by proceeding <em>through</em> a third model.
441
- For example, if each supplier has one account, and each account is associated with one account history, then the
442
- supplier model could look like this:</p><div class="code_container">
443
- <pre class="brush: ruby; gutter: false; toolbar: false">
444
- class Supplier &lt; ActiveRecord::Base
445
- has_one :account
446
- has_one :account_history, through: :account
447
- end
448
-
449
- class Account &lt; ActiveRecord::Base
450
- belongs_to :supplier
451
- has_one :account_history
452
- end
453
-
454
- class AccountHistory &lt; ActiveRecord::Base
455
- belongs_to :account
456
- end
457
-
458
- </pre>
459
- </div>
460
- <p><img src="images/has_one_through.png" alt="has_one :through Association Diagram"></p><p>The corresponding migration might look like this:</p><div class="code_container">
461
- <pre class="brush: ruby; gutter: false; toolbar: false">
462
- class CreateAccountHistories &lt; ActiveRecord::Migration
463
- def change
464
- create_table :suppliers do |t|
465
- t.string :name
466
- t.timestamps
467
- end
468
-
469
- create_table :accounts do |t|
470
- t.belongs_to :supplier, index: true
471
- t.string :account_number
472
- t.timestamps
473
- end
474
-
475
- create_table :account_histories do |t|
476
- t.belongs_to :account, index: true
477
- t.integer :credit_rating
478
- t.timestamps
479
- end
480
- end
481
- end
482
-
483
- </pre>
484
- </div>
485
- <h4 id="the-has_and_belongs_to_many-association">2.6 The <code>has_and_belongs_to_many</code> Association</h4><p>A <code>has_and_belongs_to_many</code> association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:</p><div class="code_container">
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
-
495
- </pre>
496
- </div>
497
- <p><img src="images/habtm.png" alt="has_and_belongs_to_many Association Diagram"></p><p>The corresponding migration might look like this:</p><div class="code_container">
498
- <pre class="brush: ruby; gutter: false; toolbar: false">
499
- class CreateAssembliesAndParts &lt; ActiveRecord::Migration
500
- def change
501
- create_table :assemblies do |t|
502
- t.string :name
503
- t.timestamps
504
- end
505
-
506
- create_table :parts do |t|
507
- t.string :part_number
508
- t.timestamps
509
- end
510
-
511
- create_table :assemblies_parts, id: false do |t|
512
- t.belongs_to :assembly, index: true
513
- t.belongs_to :part, index: true
514
- end
515
- end
516
- end
517
-
518
- </pre>
519
- </div>
520
- <h4 id="choosing-between-belongs_to-and-has_one">2.7 Choosing Between <code>belongs_to</code> and <code>has_one</code>
521
- </h4><p>If you want to set up a one-to-one relationship between two models, you'll need to add <code>belongs_to</code> to one, and <code>has_one</code> to the other. How do you know which is which?</p><p>The distinction is in where you place the foreign key (it goes on the table for the class declaring the <code>belongs_to</code> association), but you should give some thought to the actual meaning of the data as well. The <code>has_one</code> relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:</p><div class="code_container">
522
- <pre class="brush: ruby; gutter: false; toolbar: false">
523
- class Supplier &lt; ActiveRecord::Base
524
- has_one :account
525
- end
526
-
527
- class Account &lt; ActiveRecord::Base
528
- belongs_to :supplier
529
- end
530
-
531
- </pre>
532
- </div>
533
- <p>The corresponding migration might look like this:</p><div class="code_container">
534
- <pre class="brush: ruby; gutter: false; toolbar: false">
535
- class CreateSuppliers &lt; ActiveRecord::Migration
536
- def change
537
- create_table :suppliers do |t|
538
- t.string :name
539
- t.timestamps
540
- end
541
-
542
- create_table :accounts do |t|
543
- t.integer :supplier_id
544
- t.string :account_number
545
- t.timestamps
546
- end
547
-
548
- add_index :accounts, :supplier_id
549
- end
550
- end
551
-
552
- </pre>
553
- </div>
554
- <div class="note"><p>Using <code>t.integer :supplier_id</code> makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using <code>t.references :supplier</code> instead.</p></div><h4 id="choosing-between-has_many-:through-and-has_and_belongs_to_many">2.8 Choosing Between <code>has_many :through</code> and <code>has_and_belongs_to_many</code>
555
- </h4><p>Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use <code>has_and_belongs_to_many</code>, which allows you to make the association directly:</p><div class="code_container">
556
- <pre class="brush: ruby; gutter: false; toolbar: false">
557
- class Assembly &lt; ActiveRecord::Base
558
- has_and_belongs_to_many :parts
559
- end
560
-
561
- class Part &lt; ActiveRecord::Base
562
- has_and_belongs_to_many :assemblies
563
- end
564
-
565
- </pre>
566
- </div>
567
- <p>The second way to declare a many-to-many relationship is to use <code>has_many :through</code>. This makes the association indirectly, through a join model:</p><div class="code_container">
568
- <pre class="brush: ruby; gutter: false; toolbar: false">
569
- class Assembly &lt; ActiveRecord::Base
570
- has_many :manifests
571
- has_many :parts, through: :manifests
572
- end
573
-
574
- class Manifest &lt; ActiveRecord::Base
575
- belongs_to :assembly
576
- belongs_to :part
577
- end
578
-
579
- class Part &lt; ActiveRecord::Base
580
- has_many :manifests
581
- has_many :assemblies, through: :manifests
582
- end
583
-
584
- </pre>
585
- </div>
586
- <p>The simplest rule of thumb is that you should set up a <code>has_many :through</code> relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a <code>has_and_belongs_to_many</code> relationship (though you'll need to remember to create the joining table in the database).</p><p>You should use <code>has_many :through</code> if you need validations, callbacks, or extra attributes on the join model.</p><h4 id="polymorphic-associations">2.9 Polymorphic Associations</h4><p>A slightly more advanced twist on associations is the <em>polymorphic association</em>. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:</p><div class="code_container">
587
- <pre class="brush: ruby; gutter: false; toolbar: false">
588
- class Picture &lt; ActiveRecord::Base
589
- belongs_to :imageable, polymorphic: true
590
- end
591
-
592
- class Employee &lt; ActiveRecord::Base
593
- has_many :pictures, as: :imageable
594
- end
595
-
596
- class Product &lt; ActiveRecord::Base
597
- has_many :pictures, as: :imageable
598
- end
599
-
600
- </pre>
601
- </div>
602
- <p>You can think of a polymorphic <code>belongs_to</code> declaration as setting up an interface that any other model can use. From an instance of the <code>Employee</code> model, you can retrieve a collection of pictures: <code>@employee.pictures</code>.</p><p>Similarly, you can retrieve <code>@product.pictures</code>.</p><p>If you have an instance of the <code>Picture</code> model, you can get to its parent via <code>@picture.imageable</code>. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:</p><div class="code_container">
603
- <pre class="brush: ruby; gutter: false; toolbar: false">
604
- class CreatePictures &lt; ActiveRecord::Migration
605
- def change
606
- create_table :pictures do |t|
607
- t.string :name
608
- t.integer :imageable_id
609
- t.string :imageable_type
610
- t.timestamps
611
- end
612
-
613
- add_index :pictures, :imageable_id
614
- end
615
- end
616
-
617
- </pre>
618
- </div>
619
- <p>This migration can be simplified by using the <code>t.references</code> form:</p><div class="code_container">
620
- <pre class="brush: ruby; gutter: false; toolbar: false">
621
- class CreatePictures &lt; ActiveRecord::Migration
622
- def change
623
- create_table :pictures do |t|
624
- t.string :name
625
- t.references :imageable, polymorphic: true, index: true
626
- t.timestamps
627
- end
628
- end
629
- end
630
-
631
- </pre>
632
- </div>
633
- <p><img src="images/polymorphic.png" alt="Polymorphic Association Diagram"></p><h4 id="self-joins">2.10 Self Joins</h4><p>In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:</p><div class="code_container">
634
- <pre class="brush: ruby; gutter: false; toolbar: false">
635
- class Employee &lt; ActiveRecord::Base
636
- has_many :subordinates, class_name: "Employee",
637
- foreign_key: "manager_id"
638
-
639
- belongs_to :manager, class_name: "Employee"
640
- end
641
-
642
- </pre>
643
- </div>
644
- <p>With this setup, you can retrieve <code>@employee.subordinates</code> and <code>@employee.manager</code>.</p><p>In your migrations/schema, you will add a references column to the model itself.</p><div class="code_container">
645
- <pre class="brush: ruby; gutter: false; toolbar: false">
646
- class CreateEmployees &lt; ActiveRecord::Migration
647
- def change
648
- create_table :employees do |t|
649
- t.references :manager, index: true
650
- t.timestamps
651
- end
652
- end
653
- end
654
-
655
- </pre>
656
- </div>
657
- <h3 id="tips,-tricks,-and-warnings">3 Tips, Tricks, and Warnings</h3><p>Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:</p>
658
- <ul>
659
- <li>Controlling caching</li>
660
- <li>Avoiding name collisions</li>
661
- <li>Updating the schema</li>
662
- <li>Controlling association scope</li>
663
- <li>Bi-directional associations</li>
664
- </ul>
665
- <h4 id="controlling-caching">3.1 Controlling Caching</h4><p>All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:</p><div class="code_container">
666
- <pre class="brush: ruby; gutter: false; toolbar: false">
667
- customer.orders # retrieves orders from the database
668
- customer.orders.size # uses the cached copy of orders
669
- customer.orders.empty? # uses the cached copy of orders
670
-
671
- </pre>
672
- </div>
673
- <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 <code>true</code> to the association call:</p><div class="code_container">
674
- <pre class="brush: ruby; gutter: false; toolbar: false">
675
- customer.orders # retrieves orders from the database
676
- customer.orders.size # uses the cached copy of orders
677
- customer.orders(true).empty? # discards the cached copy of orders
678
- # and goes back to the database
679
-
680
- </pre>
681
- </div>
682
- <h4 id="avoiding-name-collisions">3.2 Avoiding Name Collisions</h4><p>You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of <code>ActiveRecord::Base</code>. The association method would override the base method and break things. For instance, <code>attributes</code> or <code>connection</code> are bad names for associations.</p><h4 id="updating-the-schema">3.3 Updating the Schema</h4><p>Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For <code>belongs_to</code> associations you need to create foreign keys, and for <code>has_and_belongs_to_many</code> associations you need to create the appropriate join table.</p><h5 id="creating-foreign-keys-for-belongs_to-associations">3.3.1 Creating Foreign Keys for <code>belongs_to</code> Associations</h5><p>When you declare a <code>belongs_to</code> association, you need to create foreign keys as appropriate. For example, consider this model:</p><div class="code_container">
683
- <pre class="brush: ruby; gutter: false; toolbar: false">
684
- class Order &lt; ActiveRecord::Base
685
- belongs_to :customer
686
- end
687
-
688
- </pre>
689
- </div>
690
- <p>This declaration needs to be backed up by the proper foreign key declaration on the orders table:</p><div class="code_container">
691
- <pre class="brush: ruby; gutter: false; toolbar: false">
692
- class CreateOrders &lt; ActiveRecord::Migration
693
- def change
694
- create_table :orders do |t|
695
- t.datetime :order_date
696
- t.string :order_number
697
- t.integer :customer_id
698
- end
699
-
700
- add_index :orders, :customer_id
701
- end
702
- end
703
-
704
- </pre>
705
- </div>
706
- <p>If you create an association some time after you build the underlying model, you need to remember to create an <code>add_column</code> migration to provide the necessary foreign key.</p><h5 id="creating-join-tables-for-has_and_belongs_to_many-associations">3.3.2 Creating Join Tables for <code>has_and_belongs_to_many</code> Associations</h5><p>If you create a <code>has_and_belongs_to_many</code> association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the <code>:join_table</code> option, Active Record creates the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.</p><div class="warning"><p>The precedence between model names is calculated using the <code>&lt;</code> operator for <code>String</code>. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers" (because the underscore '<em>' is lexicographically _less</em> than 's' in common encodings).</p></div><p>Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:</p><div class="code_container">
707
- <pre class="brush: ruby; gutter: false; toolbar: false">
708
- class Assembly &lt; ActiveRecord::Base
709
- has_and_belongs_to_many :parts
710
- end
711
-
712
- class Part &lt; ActiveRecord::Base
713
- has_and_belongs_to_many :assemblies
714
- end
715
-
716
- </pre>
717
- </div>
718
- <p>These need to be backed up by a migration to create the <code>assemblies_parts</code> table. This table should be created without a primary key:</p><div class="code_container">
719
- <pre class="brush: ruby; gutter: false; toolbar: false">
720
- class CreateAssembliesPartsJoinTable &lt; ActiveRecord::Migration
721
- def change
722
- create_table :assemblies_parts, id: false do |t|
723
- t.integer :assembly_id
724
- t.integer :part_id
725
- end
726
-
727
- add_index :assemblies_parts, :assembly_id
728
- add_index :assemblies_parts, :part_id
729
- end
730
- end
731
-
732
- </pre>
733
- </div>
734
- <p>We pass <code>id: false</code> to <code>create_table</code> because that table does not represent a model. That's required for the association to work properly. If you observe any strange behavior in a <code>has_and_belongs_to_many</code> association like mangled models IDs, or exceptions about conflicting IDs, chances are you forgot that bit.</p><h4 id="controlling-association-scope">3.4 Controlling Association Scope</h4><p>By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example:</p><div class="code_container">
735
- <pre class="brush: ruby; gutter: false; toolbar: false">
736
- module MyApplication
737
- module Business
738
- class Supplier &lt; ActiveRecord::Base
739
- has_one :account
740
- end
741
-
742
- class Account &lt; ActiveRecord::Base
743
- belongs_to :supplier
744
- end
745
- end
746
- end
747
-
748
- </pre>
749
- </div>
750
- <p>This will work fine, because both the <code>Supplier</code> and the <code>Account</code> class are defined within the same scope. But the following will <em>not</em> work, because <code>Supplier</code> and <code>Account</code> are defined in different scopes:</p><div class="code_container">
751
- <pre class="brush: ruby; gutter: false; toolbar: false">
752
- module MyApplication
753
- module Business
754
- class Supplier &lt; ActiveRecord::Base
755
- has_one :account
756
- end
757
- end
758
-
759
- module Billing
760
- class Account &lt; ActiveRecord::Base
761
- belongs_to :supplier
762
- end
763
- end
764
- end
765
-
766
- </pre>
767
- </div>
768
- <p>To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:</p><div class="code_container">
769
- <pre class="brush: ruby; gutter: false; toolbar: false">
770
- module MyApplication
771
- module Business
772
- class Supplier &lt; ActiveRecord::Base
773
- has_one :account,
774
- class_name: "MyApplication::Billing::Account"
775
- end
776
- end
777
-
778
- module Billing
779
- class Account &lt; ActiveRecord::Base
780
- belongs_to :supplier,
781
- class_name: "MyApplication::Business::Supplier"
782
- end
783
- end
784
- end
785
-
786
- </pre>
787
- </div>
788
- <h4 id="bi-directional-associations">3.5 Bi-directional Associations</h4><p>It's normal for associations to work in two directions, requiring declaration on two different models:</p><div class="code_container">
789
- <pre class="brush: ruby; gutter: false; toolbar: false">
790
- class Customer &lt; ActiveRecord::Base
791
- has_many :orders
792
- end
793
-
794
- class Order &lt; ActiveRecord::Base
795
- belongs_to :customer
796
- end
797
-
798
- </pre>
799
- </div>
800
- <p>By default, Active Record doesn't know about the connection between these associations. This can lead to two copies of an object getting out of sync:</p><div class="code_container">
801
- <pre class="brush: ruby; gutter: false; toolbar: false">
802
- c = Customer.first
803
- o = c.orders.first
804
- c.first_name == o.customer.first_name # =&gt; true
805
- c.first_name = 'Manny'
806
- c.first_name == o.customer.first_name # =&gt; false
807
-
808
- </pre>
809
- </div>
810
- <p>This happens because c and o.customer are two different in-memory representations of the same data, and neither one is automatically refreshed from changes to the other. Active Record provides the <code>:inverse_of</code> option so that you can inform it of these relations:</p><div class="code_container">
811
- <pre class="brush: ruby; gutter: false; toolbar: false">
812
- class Customer &lt; ActiveRecord::Base
813
- has_many :orders, inverse_of: :customer
814
- end
815
-
816
- class Order &lt; ActiveRecord::Base
817
- belongs_to :customer, inverse_of: :orders
818
- end
819
-
820
- </pre>
821
- </div>
822
- <p>With these changes, Active Record will only load one copy of the customer object, preventing inconsistencies and making your application more efficient:</p><div class="code_container">
823
- <pre class="brush: ruby; gutter: false; toolbar: false">
824
- c = Customer.first
825
- o = c.orders.first
826
- c.first_name == o.customer.first_name # =&gt; true
827
- c.first_name = 'Manny'
828
- c.first_name == o.customer.first_name # =&gt; true
829
-
830
- </pre>
831
- </div>
832
- <p>There are a few limitations to <code>inverse_of</code> support:</p>
833
- <ul>
834
- <li>They do not work with <code>:through</code> associations.</li>
835
- <li>They do not work with <code>:polymorphic</code> associations.</li>
836
- <li>They do not work with <code>:as</code> associations.</li>
837
- <li>For <code>belongs_to</code> associations, <code>has_many</code> inverse associations are ignored.</li>
838
- </ul>
839
- <p>Every association will attempt to automatically find the inverse association
840
- and set the <code>:inverse_of</code> option heuristically (based on the association name).
841
- Most associations with standard names will be supported. However, associations
842
- that contain the following options will not have their inverses set
843
- automatically:</p>
844
- <ul>
845
- <li>:conditions</li>
846
- <li>:through</li>
847
- <li>:polymorphic</li>
848
- <li>:foreign_key</li>
849
- </ul>
850
- <h3 id="detailed-association-reference">4 Detailed Association Reference</h3><p>The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.</p><h4 id="belongs_to-association-reference">4.1 <code>belongs_to</code> Association Reference</h4><p>The <code>belongs_to</code> association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use <code>has_one</code> instead.</p><h5 id="methods-added-by-belongs_to">4.1.1 Methods Added by <code>belongs_to</code>
851
- </h5><p>When you declare a <code>belongs_to</code> association, the declaring class automatically gains five methods related to the association:</p>
852
- <ul>
853
- <li><code>association(force_reload = false)</code></li>
854
- <li><code>association=(associate)</code></li>
855
- <li><code>build_association(attributes = {})</code></li>
856
- <li><code>create_association(attributes = {})</code></li>
857
- <li><code>create_association!(attributes = {})</code></li>
858
- </ul>
859
- <p>In all of these methods, <code>association</code> is replaced with the symbol passed as the first argument to <code>belongs_to</code>. For example, given the declaration:</p><div class="code_container">
860
- <pre class="brush: ruby; gutter: false; toolbar: false">
861
- class Order &lt; ActiveRecord::Base
862
- belongs_to :customer
863
- end
864
-
865
- </pre>
866
- </div>
867
- <p>Each instance of the order model will have these methods:</p><div class="code_container">
868
- <pre class="brush: ruby; gutter: false; toolbar: false">
869
- customer
870
- customer=
871
- build_customer
872
- create_customer
873
- create_customer!
874
-
875
- </pre>
876
- </div>
877
- <div class="note"><p>When initializing a new <code>has_one</code> or <code>belongs_to</code> association you must use the <code>build_</code> prefix to build the association, rather than the <code>association.build</code> method that would be used for <code>has_many</code> or <code>has_and_belongs_to_many</code> associations. To create one, use the <code>create_</code> prefix.</p></div><h6 id="methods-added-by-belongs_to-association(force_reload-=-false)">4.1.1.1 <code>association(force_reload = false)</code>
878
- </h6><p>The <code>association</code> method returns the associated object, if any. If no associated object is found, it returns <code>nil</code>.</p><div class="code_container">
879
- <pre class="brush: ruby; gutter: false; toolbar: false">
880
- @customer = @order.customer
881
-
882
- </pre>
883
- </div>
884
- <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 <code>true</code> as the <code>force_reload</code> argument.</p><h6 id="methods-added-by-belongs_to-association=(associate)">4.1.1.2 <code>association=(associate)</code>
885
- </h6><p>The <code>association=</code> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.</p><div class="code_container">
886
- <pre class="brush: ruby; gutter: false; toolbar: false">
887
- @order.customer = @customer
888
-
889
- </pre>
890
- </div>
891
- <h6 id="methods-added-by-belongs_to-build_association(attributes-=-{})">4.1.1.3 <code>build_association(attributes = {})</code>
892
- </h6><p>The <code>build_association</code> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will <em>not</em> yet be saved.</p><div class="code_container">
893
- <pre class="brush: ruby; gutter: false; toolbar: false">
894
- @customer = @order.build_customer(customer_number: 123,
895
- customer_name: "John Doe")
896
-
897
- </pre>
898
- </div>
899
- <h6 id="methods-added-by-belongs_to-create_association(attributes-=-{})">4.1.1.4 <code>create_association(attributes = {})</code>
900
- </h6><p>The <code>create_association</code> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through this object's foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object <em>will</em> be saved.</p><div class="code_container">
901
- <pre class="brush: ruby; gutter: false; toolbar: false">
902
- @customer = @order.create_customer(customer_number: 123,
903
- customer_name: "John Doe")
904
-
905
- </pre>
906
- </div>
907
- <h6 id="methods-added-by-belongs_to-create_association-bang(attributes-=-{})">4.1.1.5 <code>create_association!(attributes = {})</code>
908
- </h6><p>Does the same as <code>create_association</code> above, but raises <code>ActiveRecord::RecordInvalid</code> if the record is invalid.</p><h5 id="options-for-belongs_to">4.1.2 Options for <code>belongs_to</code>
909
- </h5><p>While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the <code>belongs_to</code> association reference. Such customizations can easily be accomplished by passing options and scope blocks when you create the association. For example, this association uses two such options:</p><div class="code_container">
910
- <pre class="brush: ruby; gutter: false; toolbar: false">
911
- class Order &lt; ActiveRecord::Base
912
- belongs_to :customer, dependent: :destroy,
913
- counter_cache: true
914
- end
915
-
916
- </pre>
917
- </div>
918
- <p>The <code>belongs_to</code> association supports these options:</p>
919
- <ul>
920
- <li><code>:autosave</code></li>
921
- <li><code>:class_name</code></li>
922
- <li><code>:counter_cache</code></li>
923
- <li><code>:dependent</code></li>
924
- <li><code>:foreign_key</code></li>
925
- <li><code>:inverse_of</code></li>
926
- <li><code>:polymorphic</code></li>
927
- <li><code>:touch</code></li>
928
- <li><code>:validate</code></li>
929
- </ul>
930
- <h6 id="options-for-belongs_to-:autosave">4.1.2.1 <code>:autosave</code>
931
- </h6><p>If you set the <code>:autosave</code> option to <code>true</code>, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.</p><h6 id="options-for-belongs_to-:class_name">4.1.2.2 <code>:class_name</code>
932
- </h6><p>If the name of the other model cannot be derived from the association name, you can use the <code>:class_name</code> 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 <code>Patron</code>, you'd set things up this way:</p><div class="code_container">
933
- <pre class="brush: ruby; gutter: false; toolbar: false">
934
- class Order &lt; ActiveRecord::Base
935
- belongs_to :customer, class_name: "Patron"
936
- end
937
-
938
- </pre>
939
- </div>
940
- <h6 id=":counter_cache">4.1.2.3 <code>:counter_cache</code>
941
- </h6><p>The <code>:counter_cache</code> option can be used to make finding the number of belonging objects more efficient. Consider these models:</p><div class="code_container">
942
- <pre class="brush: ruby; gutter: false; toolbar: false">
943
- class Order &lt; ActiveRecord::Base
944
- belongs_to :customer
945
- end
946
- class Customer &lt; ActiveRecord::Base
947
- has_many :orders
948
- end
949
-
950
- </pre>
951
- </div>
952
- <p>With these declarations, asking for the value of <code>@customer.orders.size</code> requires making a call to the database to perform a <code>COUNT(*)</code> query. To avoid this call, you can add a counter cache to the <em>belonging</em> model:</p><div class="code_container">
953
- <pre class="brush: ruby; gutter: false; toolbar: false">
954
- class Order &lt; ActiveRecord::Base
955
- belongs_to :customer, counter_cache: true
956
- end
957
- class Customer &lt; ActiveRecord::Base
958
- has_many :orders
959
- end
960
-
961
- </pre>
962
- </div>
963
- <p>With this declaration, Rails will keep the cache value up to date, and then return that value in response to the <code>size</code> method.</p><p>Although the <code>:counter_cache</code> option is specified on the model that includes the <code>belongs_to</code> 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 <code>orders_count</code> to the <code>Customer</code> model. You can override the default column name if you need to:</p><div class="code_container">
964
- <pre class="brush: ruby; gutter: false; toolbar: false">
965
- class Order &lt; ActiveRecord::Base
966
- belongs_to :customer, counter_cache: :count_of_orders
967
- end
968
- class Customer &lt; ActiveRecord::Base
969
- has_many :orders
970
- end
971
-
972
- </pre>
973
- </div>
974
- <p>Counter cache columns are added to the containing model's list of read-only attributes through <code>attr_readonly</code>.</p><h6 id="options-for-belongs_to-:dependent">4.1.2.4 <code>:dependent</code>
975
- </h6><p>If you set the <code>:dependent</code> option to:</p>
976
- <ul>
977
- <li>
978
- <code>:destroy</code>, when the object is destroyed, <code>destroy</code> will be called on its
979
- associated objects.</li>
980
- <li>
981
- <code>:delete</code>, when the object is destroyed, all its associated objects will be
982
- deleted directly from the database without calling their <code>destroy</code> method.</li>
983
- </ul>
984
- <div class="warning"><p>You should not specify this option on a <code>belongs_to</code> association that is connected with a <code>has_many</code> association on the other class. Doing so can lead to orphaned records in your database.</p></div><h6 id="options-for-belongs_to-:foreign_key">4.1.2.5 <code>:foreign_key</code>
985
- </h6><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 <code>_id</code> added. The <code>:foreign_key</code> option lets you set the name of the foreign key directly:</p><div class="code_container">
986
- <pre class="brush: ruby; gutter: false; toolbar: false">
987
- class Order &lt; ActiveRecord::Base
988
- belongs_to :customer, class_name: "Patron",
989
- foreign_key: "patron_id"
990
- end
991
-
992
- </pre>
993
- </div>
994
- <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><h6 id="options-for-belongs_to-:inverse_of">4.1.2.6 <code>:inverse_of</code>
995
- </h6><p>The <code>:inverse_of</code> option specifies the name of the <code>has_many</code> or <code>has_one</code> association that is the inverse of this association. Does not work in combination with the <code>:polymorphic</code> options.</p><div class="code_container">
996
- <pre class="brush: ruby; gutter: false; toolbar: false">
997
- class Customer &lt; ActiveRecord::Base
998
- has_many :orders, inverse_of: :customer
999
- end
1000
-
1001
- class Order &lt; ActiveRecord::Base
1002
- belongs_to :customer, inverse_of: :orders
1003
- end
1004
-
1005
- </pre>
1006
- </div>
1007
- <h6 id=":polymorphic">4.1.2.7 <code>:polymorphic</code>
1008
- </h6><p>Passing <code>true</code> to the <code>:polymorphic</code> option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.</p><h6 id=":touch">4.1.2.8 <code>:touch</code>
1009
- </h6><p>If you set the <code>:touch</code> option to <code>:true</code>, then the <code>updated_at</code> or <code>updated_on</code> timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:</p><div class="code_container">
1010
- <pre class="brush: ruby; gutter: false; toolbar: false">
1011
- class Order &lt; ActiveRecord::Base
1012
- belongs_to :customer, touch: true
1013
- end
1014
-
1015
- class Customer &lt; ActiveRecord::Base
1016
- has_many :orders
1017
- end
1018
-
1019
- </pre>
1020
- </div>
1021
- <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><div class="code_container">
1022
- <pre class="brush: ruby; gutter: false; toolbar: false">
1023
- class Order &lt; ActiveRecord::Base
1024
- belongs_to :customer, touch: :orders_updated_at
1025
- end
1026
-
1027
- </pre>
1028
- </div>
1029
- <h6 id="options-for-belongs_to-:validate">4.1.2.9 <code>:validate</code>
1030
- </h6><p>If you set the <code>:validate</code> option to <code>true</code>, then associated objects will be validated whenever you save this object. By default, this is <code>false</code>: associated objects will not be validated when this object is saved.</p><h5 id="scopes-for-belongs_to">4.1.3 Scopes for <code>belongs_to</code>
1031
- </h5><p>There may be times when you wish to customize the query used by <code>belongs_to</code>. Such customizations can be achieved via a scope block. For example:</p><div class="code_container">
1032
- <pre class="brush: ruby; gutter: false; toolbar: false">
1033
- class Order &lt; ActiveRecord::Base
1034
- belongs_to :customer, -&gt; { where active: true },
1035
- dependent: :destroy
1036
- end
1037
-
1038
- </pre>
1039
- </div>
1040
- <p>You can use any of the standard <a href="active_record_querying.html">querying methods</a> inside the scope block. The following ones are discussed below:</p>
1041
- <ul>
1042
- <li><code>where</code></li>
1043
- <li><code>includes</code></li>
1044
- <li><code>readonly</code></li>
1045
- <li><code>select</code></li>
1046
- </ul>
1047
- <h6 id="scopes-for-belongs_to-where">4.1.3.1 <code>where</code>
1048
- </h6><p>The <code>where</code> method lets you specify the conditions that the associated object must meet.</p><div class="code_container">
1049
- <pre class="brush: ruby; gutter: false; toolbar: false">
1050
- class Order &lt; ActiveRecord::Base
1051
- belongs_to :customer, -&gt; { where active: true }
1052
- end
1053
-
1054
- </pre>
1055
- </div>
1056
- <h6 id="scopes-for-belongs_to-includes">4.1.3.2 <code>includes</code>
1057
- </h6><p>You can use the <code>includes</code> method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p><div class="code_container">
1058
- <pre class="brush: ruby; gutter: false; toolbar: false">
1059
- class LineItem &lt; ActiveRecord::Base
1060
- belongs_to :order
1061
- end
1062
-
1063
- class Order &lt; ActiveRecord::Base
1064
- belongs_to :customer
1065
- has_many :line_items
1066
- end
1067
-
1068
- class Customer &lt; ActiveRecord::Base
1069
- has_many :orders
1070
- end
1071
-
1072
- </pre>
1073
- </div>
1074
- <p>If you frequently retrieve customers directly from line items (<code>@line_item.order.customer</code>), then you can make your code somewhat more efficient by including customers in the association from line items to orders:</p><div class="code_container">
1075
- <pre class="brush: ruby; gutter: false; toolbar: false">
1076
- class LineItem &lt; ActiveRecord::Base
1077
- belongs_to :order, -&gt; { includes :customer }
1078
- end
1079
-
1080
- class Order &lt; ActiveRecord::Base
1081
- belongs_to :customer
1082
- has_many :line_items
1083
- end
1084
-
1085
- class Customer &lt; ActiveRecord::Base
1086
- has_many :orders
1087
- end
1088
-
1089
- </pre>
1090
- </div>
1091
- <div class="note"><p>There's no need to use <code>includes</code> for immediate associations - that is, if you have <code>Order belongs_to :customer</code>, then the customer is eager-loaded automatically when it's needed.</p></div><h6 id="scopes-for-belongs_to-readonly">4.1.3.3 <code>readonly</code>
1092
- </h6><p>If you use <code>readonly</code>, then the associated object will be read-only when retrieved via the association.</p><h6 id="scopes-for-belongs_to-select">4.1.3.4 <code>select</code>
1093
- </h6><p>The <code>select</code> method lets you override the SQL <code>SELECT</code> clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.</p><div class="info"><p>If you use the <code>select</code> method on a <code>belongs_to</code> association, you should also set the <code>:foreign_key</code> option to guarantee the correct results.</p></div><h5 id="belongs_to-association-reference-do-any-associated-objects-exist-questionmark">4.1.4 Do Any Associated Objects Exist?</h5><p>You can see if any associated objects exist by using the <code>association.nil?</code> method:</p><div class="code_container">
1094
- <pre class="brush: ruby; gutter: false; toolbar: false">
1095
- if @order.customer.nil?
1096
- @msg = "No customer found for this order"
1097
- end
1098
-
1099
- </pre>
1100
- </div>
1101
- <h5 id="belongs_to-association-reference-when-are-objects-saved-questionmark">4.1.5 When are Objects Saved?</h5><p>Assigning an object to a <code>belongs_to</code> association does <em>not</em> automatically save the object. It does not save the associated object either.</p><h4 id="has_one-association-reference">4.2 <code>has_one</code> Association Reference</h4><p>The <code>has_one</code> 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 <code>belongs_to</code> instead.</p><h5 id="methods-added-by-has_one">4.2.1 Methods Added by <code>has_one</code>
1102
- </h5><p>When you declare a <code>has_one</code> association, the declaring class automatically gains five methods related to the association:</p>
1103
- <ul>
1104
- <li><code>association(force_reload = false)</code></li>
1105
- <li><code>association=(associate)</code></li>
1106
- <li><code>build_association(attributes = {})</code></li>
1107
- <li><code>create_association(attributes = {})</code></li>
1108
- <li><code>create_association!(attributes = {})</code></li>
1109
- </ul>
1110
- <p>In all of these methods, <code>association</code> is replaced with the symbol passed as the first argument to <code>has_one</code>. For example, given the declaration:</p><div class="code_container">
1111
- <pre class="brush: ruby; gutter: false; toolbar: false">
1112
- class Supplier &lt; ActiveRecord::Base
1113
- has_one :account
1114
- end
1115
-
1116
- </pre>
1117
- </div>
1118
- <p>Each instance of the <code>Supplier</code> model will have these methods:</p><div class="code_container">
1119
- <pre class="brush: ruby; gutter: false; toolbar: false">
1120
- account
1121
- account=
1122
- build_account
1123
- create_account
1124
- create_account!
1125
-
1126
- </pre>
1127
- </div>
1128
- <div class="note"><p>When initializing a new <code>has_one</code> or <code>belongs_to</code> association you must use the <code>build_</code> prefix to build the association, rather than the <code>association.build</code> method that would be used for <code>has_many</code> or <code>has_and_belongs_to_many</code> associations. To create one, use the <code>create_</code> prefix.</p></div><h6 id="methods-added-by-has_one-association(force_reload-=-false)">4.2.1.1 <code>association(force_reload = false)</code>
1129
- </h6><p>The <code>association</code> method returns the associated object, if any. If no associated object is found, it returns <code>nil</code>.</p><div class="code_container">
1130
- <pre class="brush: ruby; gutter: false; toolbar: false">
1131
- @account = @supplier.account
1132
-
1133
- </pre>
1134
- </div>
1135
- <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 <code>true</code> as the <code>force_reload</code> argument.</p><h6 id="methods-added-by-has_one-association=(associate)">4.2.1.2 <code>association=(associate)</code>
1136
- </h6><p>The <code>association=</code> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.</p><div class="code_container">
1137
- <pre class="brush: ruby; gutter: false; toolbar: false">
1138
- @supplier.account = @account
1139
-
1140
- </pre>
1141
- </div>
1142
- <h6 id="methods-added-by-has_one-build_association(attributes-=-{})">4.2.1.3 <code>build_association(attributes = {})</code>
1143
- </h6><p>The <code>build_association</code> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will <em>not</em> yet be saved.</p><div class="code_container">
1144
- <pre class="brush: ruby; gutter: false; toolbar: false">
1145
- @account = @supplier.build_account(terms: "Net 30")
1146
-
1147
- </pre>
1148
- </div>
1149
- <h6 id="methods-added-by-has_one-create_association(attributes-=-{})">4.2.1.4 <code>create_association(attributes = {})</code>
1150
- </h6><p>The <code>create_association</code> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through 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><div class="code_container">
1151
- <pre class="brush: ruby; gutter: false; toolbar: false">
1152
- @account = @supplier.create_account(terms: "Net 30")
1153
-
1154
- </pre>
1155
- </div>
1156
- <h6 id="methods-added-by-has_one-create_association-bang(attributes-=-{})">4.2.1.5 <code>create_association!(attributes = {})</code>
1157
- </h6><p>Does the same as <code>create_association</code> above, but raises <code>ActiveRecord::RecordInvalid</code> if the record is invalid.</p><h5 id="options-for-has_one">4.2.2 Options for <code>has_one</code>
1158
- </h5><p>While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the <code>has_one</code> association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:</p><div class="code_container">
1159
- <pre class="brush: ruby; gutter: false; toolbar: false">
1160
- class Supplier &lt; ActiveRecord::Base
1161
- has_one :account, class_name: "Billing", dependent: :nullify
1162
- end
1163
-
1164
- </pre>
1165
- </div>
1166
- <p>The <code>has_one</code> association supports these options:</p>
1167
- <ul>
1168
- <li><code>:as</code></li>
1169
- <li><code>:autosave</code></li>
1170
- <li><code>:class_name</code></li>
1171
- <li><code>:dependent</code></li>
1172
- <li><code>:foreign_key</code></li>
1173
- <li><code>:inverse_of</code></li>
1174
- <li><code>:primary_key</code></li>
1175
- <li><code>:source</code></li>
1176
- <li><code>:source_type</code></li>
1177
- <li><code>:through</code></li>
1178
- <li><code>:validate</code></li>
1179
- </ul>
1180
- <h6 id="options-for-has_one-:as">4.2.2.1 <code>:as</code>
1181
- </h6><p>Setting the <code>:as</code> option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.</p><h6 id="options-for-has_one-:autosave">4.2.2.2 <code>:autosave</code>
1182
- </h6><p>If you set the <code>:autosave</code> option to <code>true</code>, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.</p><h6 id="options-for-has_one-:class_name">4.2.2.3 <code>:class_name</code>
1183
- </h6><p>If the name of the other model cannot be derived from the association name, you can use the <code>:class_name</code> option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is <code>Billing</code>, you'd set things up this way:</p><div class="code_container">
1184
- <pre class="brush: ruby; gutter: false; toolbar: false">
1185
- class Supplier &lt; ActiveRecord::Base
1186
- has_one :account, class_name: "Billing"
1187
- end
1188
-
1189
- </pre>
1190
- </div>
1191
- <h6 id="options-for-has_one-:dependent">4.2.2.4 <code>:dependent</code>
1192
- </h6><p>Controls what happens to the associated object when its owner is destroyed:</p>
1193
- <ul>
1194
- <li>
1195
- <code>:destroy</code> causes the associated object to also be destroyed</li>
1196
- <li>
1197
- <code>:delete</code> causes the associated object to be deleted directly from the database (so callbacks will not execute)</li>
1198
- <li>
1199
- <code>:nullify</code> causes the foreign key to be set to <code>NULL</code>. Callbacks are not executed.</li>
1200
- <li>
1201
- <code>:restrict_with_exception</code> causes an exception to be raised if there is an associated record</li>
1202
- <li>
1203
- <code>:restrict_with_error</code> causes an error to be added to the owner if there is an associated object</li>
1204
- </ul>
1205
- <p>It's necessary not to set or leave <code>:nullify</code> option for those associations
1206
- that have <code>NOT NULL</code> database constraints. If you don't set <code>dependent</code> to
1207
- destroy such associations you won't be able to change the associated object
1208
- because initial associated object foreign key will be set to unallowed <code>NULL</code>
1209
- value.</p><h6 id="options-for-has_one-:foreign_key">4.2.2.5 <code>:foreign_key</code>
1210
- </h6><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 <code>_id</code> added. The <code>:foreign_key</code> option lets you set the name of the foreign key directly:</p><div class="code_container">
1211
- <pre class="brush: ruby; gutter: false; toolbar: false">
1212
- class Supplier &lt; ActiveRecord::Base
1213
- has_one :account, foreign_key: "supp_id"
1214
- end
1215
-
1216
- </pre>
1217
- </div>
1218
- <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><h6 id="options-for-has_one-:inverse_of">4.2.2.6 <code>:inverse_of</code>
1219
- </h6><p>The <code>:inverse_of</code> option specifies the name of the <code>belongs_to</code> association that is the inverse of this association. Does not work in combination with the <code>:through</code> or <code>:as</code> options.</p><div class="code_container">
1220
- <pre class="brush: ruby; gutter: false; toolbar: false">
1221
- class Supplier &lt; ActiveRecord::Base
1222
- has_one :account, inverse_of: :supplier
1223
- end
1224
-
1225
- class Account &lt; ActiveRecord::Base
1226
- belongs_to :supplier, inverse_of: :account
1227
- end
1228
-
1229
- </pre>
1230
- </div>
1231
- <h6 id="options-for-has_one-:primary_key">4.2.2.7 <code>:primary_key</code>
1232
- </h6><p>By convention, Rails assumes that the column used to hold the primary key of this model is <code>id</code>. You can override this and explicitly specify the primary key with the <code>:primary_key</code> option.</p><h6 id="options-for-has_one-:source">4.2.2.8 <code>:source</code>
1233
- </h6><p>The <code>:source</code> option specifies the source association name for a <code>has_one :through</code> association.</p><h6 id="options-for-has_one-:source_type">4.2.2.9 <code>:source_type</code>
1234
- </h6><p>The <code>:source_type</code> option specifies the source association type for a <code>has_one :through</code> association that proceeds through a polymorphic association.</p><h6 id="options-for-has_one-:through">4.2.2.10 <code>:through</code>
1235
- </h6><p>The <code>:through</code> option specifies a join model through which to perform the query. <code>has_one :through</code> associations were discussed in detail <a href="#the-has-one-through-association">earlier in this guide</a>.</p><h6 id="options-for-has_one-:validate">4.2.2.11 <code>:validate</code>
1236
- </h6><p>If you set the <code>:validate</code> option to <code>true</code>, then associated objects will be validated whenever you save this object. By default, this is <code>false</code>: associated objects will not be validated when this object is saved.</p><h5 id="scopes-for-has_one">4.2.3 Scopes for <code>has_one</code>
1237
- </h5><p>There may be times when you wish to customize the query used by <code>has_one</code>. Such customizations can be achieved via a scope block. For example:</p><div class="code_container">
1238
- <pre class="brush: ruby; gutter: false; toolbar: false">
1239
- class Supplier &lt; ActiveRecord::Base
1240
- has_one :account, -&gt; { where active: true }
1241
- end
1242
-
1243
- </pre>
1244
- </div>
1245
- <p>You can use any of the standard <a href="active_record_querying.html">querying methods</a> inside the scope block. The following ones are discussed below:</p>
1246
- <ul>
1247
- <li><code>where</code></li>
1248
- <li><code>includes</code></li>
1249
- <li><code>readonly</code></li>
1250
- <li><code>select</code></li>
1251
- </ul>
1252
- <h6 id="scopes-for-has_one-where">4.2.3.1 <code>where</code>
1253
- </h6><p>The <code>where</code> method lets you specify the conditions that the associated object must meet.</p><div class="code_container">
1254
- <pre class="brush: ruby; gutter: false; toolbar: false">
1255
- class Supplier &lt; ActiveRecord::Base
1256
- has_one :account, -&gt; { where "confirmed = 1" }
1257
- end
1258
-
1259
- </pre>
1260
- </div>
1261
- <h6 id="scopes-for-has_one-includes">4.2.3.2 <code>includes</code>
1262
- </h6><p>You can use the <code>includes</code> method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p><div class="code_container">
1263
- <pre class="brush: ruby; gutter: false; toolbar: false">
1264
- class Supplier &lt; ActiveRecord::Base
1265
- has_one :account
1266
- end
1267
-
1268
- class Account &lt; ActiveRecord::Base
1269
- belongs_to :supplier
1270
- belongs_to :representative
1271
- end
1272
-
1273
- class Representative &lt; ActiveRecord::Base
1274
- has_many :accounts
1275
- end
1276
-
1277
- </pre>
1278
- </div>
1279
- <p>If you frequently retrieve representatives directly from suppliers (<code>@supplier.account.representative</code>), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:</p><div class="code_container">
1280
- <pre class="brush: ruby; gutter: false; toolbar: false">
1281
- class Supplier &lt; ActiveRecord::Base
1282
- has_one :account, -&gt; { includes :representative }
1283
- end
1284
-
1285
- class Account &lt; ActiveRecord::Base
1286
- belongs_to :supplier
1287
- belongs_to :representative
1288
- end
1289
-
1290
- class Representative &lt; ActiveRecord::Base
1291
- has_many :accounts
1292
- end
1293
-
1294
- </pre>
1295
- </div>
1296
- <h6 id="scopes-for-has_one-readonly">4.2.3.3 <code>readonly</code>
1297
- </h6><p>If you use the <code>readonly</code> method, then the associated object will be read-only when retrieved via the association.</p><h6 id="scopes-for-has_one-select">4.2.3.4 <code>select</code>
1298
- </h6><p>The <code>select</code> method lets you override the SQL <code>SELECT</code> clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.</p><h5 id="has_one-association-reference-do-any-associated-objects-exist-questionmark">4.2.4 Do Any Associated Objects Exist?</h5><p>You can see if any associated objects exist by using the <code>association.nil?</code> method:</p><div class="code_container">
1299
- <pre class="brush: ruby; gutter: false; toolbar: false">
1300
- if @supplier.account.nil?
1301
- @msg = "No account found for this supplier"
1302
- end
1303
-
1304
- </pre>
1305
- </div>
1306
- <h5 id="has_one-association-reference-when-are-objects-saved-questionmark">4.2.5 When are Objects Saved?</h5><p>When you assign an object to a <code>has_one</code> 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><p>If either of these saves fails due to validation errors, then the assignment statement returns <code>false</code> and the assignment itself is cancelled.</p><p>If the parent object (the one declaring the <code>has_one</code> association) is unsaved (that is, <code>new_record?</code> returns <code>true</code>) then the child objects are not saved. They will automatically when the parent object is saved.</p><p>If you want to assign an object to a <code>has_one</code> association without saving the object, use the <code>association.build</code> method.</p><h4 id="has_many-association-reference">4.3 <code>has_many</code> Association Reference</h4><p>The <code>has_many</code> 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><h5 id="methods-added-by-has_many">4.3.1 Methods Added by <code>has_many</code>
1307
- </h5><p>When you declare a <code>has_many</code> association, the declaring class automatically gains 16 methods related to the association:</p>
1308
- <ul>
1309
- <li><code>collection(force_reload = false)</code></li>
1310
- <li><code>collection&lt;&lt;(object, ...)</code></li>
1311
- <li><code>collection.delete(object, ...)</code></li>
1312
- <li><code>collection.destroy(object, ...)</code></li>
1313
- <li><code>collection=objects</code></li>
1314
- <li><code>collection_singular_ids</code></li>
1315
- <li><code>collection_singular_ids=ids</code></li>
1316
- <li><code>collection.clear</code></li>
1317
- <li><code>collection.empty?</code></li>
1318
- <li><code>collection.size</code></li>
1319
- <li><code>collection.find(...)</code></li>
1320
- <li><code>collection.where(...)</code></li>
1321
- <li><code>collection.exists?(...)</code></li>
1322
- <li><code>collection.build(attributes = {}, ...)</code></li>
1323
- <li><code>collection.create(attributes = {})</code></li>
1324
- <li><code>collection.create!(attributes = {})</code></li>
1325
- </ul>
1326
- <p>In all of these methods, <code>collection</code> is replaced with the symbol passed as the first argument to <code>has_many</code>, and <code>collection_singular</code> is replaced with the singularized version of that symbol. For example, given the declaration:</p><div class="code_container">
1327
- <pre class="brush: ruby; gutter: false; toolbar: false">
1328
- class Customer &lt; ActiveRecord::Base
1329
- has_many :orders
1330
- end
1331
-
1332
- </pre>
1333
- </div>
1334
- <p>Each instance of the customer model will have these methods:</p><div class="code_container">
1335
- <pre class="brush: ruby; gutter: false; toolbar: false">
1336
- orders(force_reload = false)
1337
- orders&lt;&lt;(object, ...)
1338
- orders.delete(object, ...)
1339
- orders.destroy(object, ...)
1340
- orders=objects
1341
- order_ids
1342
- order_ids=ids
1343
- orders.clear
1344
- orders.empty?
1345
- orders.size
1346
- orders.find(...)
1347
- orders.where(...)
1348
- orders.exists?(...)
1349
- orders.build(attributes = {}, ...)
1350
- orders.create(attributes = {})
1351
- orders.create!(attributes = {})
1352
-
1353
- </pre>
1354
- </div>
1355
- <h6 id="methods-added-by-has_many-collection(force_reload-=-false)">4.3.1.1 <code>collection(force_reload = false)</code>
1356
- </h6><p>The <code>collection</code> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.</p><div class="code_container">
1357
- <pre class="brush: ruby; gutter: false; toolbar: false">
1358
- @orders = @customer.orders
1359
-
1360
- </pre>
1361
- </div>
1362
- <h6 id="methods-added-by-has_many-collection&lt;&lt;(object,-...)">4.3.1.2 <code>collection&lt;&lt;(object, ...)</code>
1363
- </h6><p>The <code>collection&lt;&lt;</code> method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.</p><div class="code_container">
1364
- <pre class="brush: ruby; gutter: false; toolbar: false">
1365
- @customer.orders &lt;&lt; @order1
1366
-
1367
- </pre>
1368
- </div>
1369
- <h6 id="methods-added-by-has_many-collection.delete(object,-...)">4.3.1.3 <code>collection.delete(object, ...)</code>
1370
- </h6><p>The <code>collection.delete</code> method removes one or more objects from the collection by setting their foreign keys to <code>NULL</code>.</p><div class="code_container">
1371
- <pre class="brush: ruby; gutter: false; toolbar: false">
1372
- @customer.orders.delete(@order1)
1373
-
1374
- </pre>
1375
- </div>
1376
- <div class="warning"><p>Additionally, objects will be destroyed if they're associated with <code>dependent: :destroy</code>, and deleted if they're associated with <code>dependent: :delete_all</code>.</p></div><h6 id="methods-added-by-has_many-collection.destroy(object,-...)">4.3.1.4 <code>collection.destroy(object, ...)</code>
1377
- </h6><p>The <code>collection.destroy</code> method removes one or more objects from the collection by running <code>destroy</code> on each object.</p><div class="code_container">
1378
- <pre class="brush: ruby; gutter: false; toolbar: false">
1379
- @customer.orders.destroy(@order1)
1380
-
1381
- </pre>
1382
- </div>
1383
- <div class="warning"><p>Objects will <em>always</em> be removed from the database, ignoring the <code>:dependent</code> option.</p></div><h6 id="methods-added-by-has_many-collection=objects">4.3.1.5 <code>collection=objects</code>
1384
- </h6><p>The <code>collection=</code> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.</p><h6 id="methods-added-by-has_many-collection_singular_ids">4.3.1.6 <code>collection_singular_ids</code>
1385
- </h6><p>The <code>collection_singular_ids</code> method returns an array of the ids of the objects in the collection.</p><div class="code_container">
1386
- <pre class="brush: ruby; gutter: false; toolbar: false">
1387
- @order_ids = @customer.order_ids
1388
-
1389
- </pre>
1390
- </div>
1391
- <h6 id="methods-added-by-has_many-collection_singular_ids=ids">4.3.1.7 <code>collection_singular_ids=ids</code>
1392
- </h6><p>The <code>collection_singular_ids=</code> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.</p><h6 id="methods-added-by-has_many-collection.clear">4.3.1.8 <code>collection.clear</code>
1393
- </h6><p>The <code>collection.clear</code> method removes every object from the collection. This destroys the associated objects if they are associated with <code>dependent: :destroy</code>, deletes them directly from the database if <code>dependent: :delete_all</code>, and otherwise sets their foreign keys to <code>NULL</code>.</p><h6 id="methods-added-by-has_many-collection.empty-questionmark">4.3.1.9 <code>collection.empty?</code>
1394
- </h6><p>The <code>collection.empty?</code> method returns <code>true</code> if the collection does not contain any associated objects.</p><div class="code_container">
1395
- <pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
1396
- &lt;% if @customer.orders.empty? %&gt;
1397
- No Orders Found
1398
- &lt;% end %&gt;
1399
-
1400
- </pre>
1401
- </div>
1402
- <h6 id="methods-added-by-has_many-collection.size">4.3.1.10 <code>collection.size</code>
1403
- </h6><p>The <code>collection.size</code> method returns the number of objects in the collection.</p><div class="code_container">
1404
- <pre class="brush: ruby; gutter: false; toolbar: false">
1405
- @order_count = @customer.orders.size
1406
-
1407
- </pre>
1408
- </div>
1409
- <h6 id="methods-added-by-has_many-collection.find(...)">4.3.1.11 <code>collection.find(...)</code>
1410
- </h6><p>The <code>collection.find</code> method finds objects within the collection. It uses the same syntax and options as <code>ActiveRecord::Base.find</code>.</p><div class="code_container">
1411
- <pre class="brush: ruby; gutter: false; toolbar: false">
1412
- @open_orders = @customer.orders.find(1)
1413
-
1414
- </pre>
1415
- </div>
1416
- <h6 id="methods-added-by-has_many-collection.where(...)">4.3.1.12 <code>collection.where(...)</code>
1417
- </h6><p>The <code>collection.where</code> 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><div class="code_container">
1418
- <pre class="brush: ruby; gutter: false; toolbar: false">
1419
- @open_orders = @customer.orders.where(open: true) # No query yet
1420
- @open_order = @open_orders.first # Now the database will be queried
1421
-
1422
- </pre>
1423
- </div>
1424
- <h6 id="methods-added-by-has_many-collection.exists-questionmark(...)">4.3.1.13 <code>collection.exists?(...)</code>
1425
- </h6><p>The <code>collection.exists?</code> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as <code>ActiveRecord::Base.exists?</code>.</p><h6 id="collection.build(attributes-=-{},-...)">4.3.1.14 <code>collection.build(attributes = {}, ...)</code>
1426
- </h6><p>The <code>collection.build</code> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will <em>not</em> yet be saved.</p><div class="code_container">
1427
- <pre class="brush: ruby; gutter: false; toolbar: false">
1428
- @order = @customer.orders.build(order_date: Time.now,
1429
- order_number: "A12345")
1430
-
1431
- </pre>
1432
- </div>
1433
- <h6 id="methods-added-by-has_many-collection.create(attributes-=-{})">4.3.1.15 <code>collection.create(attributes = {})</code>
1434
- </h6><p>The <code>collection.create</code> 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><div class="code_container">
1435
- <pre class="brush: ruby; gutter: false; toolbar: false">
1436
- @order = @customer.orders.create(order_date: Time.now,
1437
- order_number: "A12345")
1438
-
1439
- </pre>
1440
- </div>
1441
- <h6 id="methods-added-by-has_many-collection.create-bang(attributes-=-{})">4.3.1.16 <code>collection.create!(attributes = {})</code>
1442
- </h6><p>Does the same as <code>collection.create</code> above, but raises <code>ActiveRecord::RecordInvalid</code> if the record is invalid.</p><h5 id="options-for-has_many">4.3.2 Options for <code>has_many</code>
1443
- </h5><p>While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the <code>has_many</code> association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:</p><div class="code_container">
1444
- <pre class="brush: ruby; gutter: false; toolbar: false">
1445
- class Customer &lt; ActiveRecord::Base
1446
- has_many :orders, dependent: :delete_all, validate: :false
1447
- end
1448
-
1449
- </pre>
1450
- </div>
1451
- <p>The <code>has_many</code> association supports these options:</p>
1452
- <ul>
1453
- <li><code>:as</code></li>
1454
- <li><code>:autosave</code></li>
1455
- <li><code>:class_name</code></li>
1456
- <li><code>:dependent</code></li>
1457
- <li><code>:foreign_key</code></li>
1458
- <li><code>:inverse_of</code></li>
1459
- <li><code>:primary_key</code></li>
1460
- <li><code>:source</code></li>
1461
- <li><code>:source_type</code></li>
1462
- <li><code>:through</code></li>
1463
- <li><code>:validate</code></li>
1464
- </ul>
1465
- <h6 id="options-for-has_many-:as">4.3.2.1 <code>:as</code>
1466
- </h6><p>Setting the <code>:as</code> option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>.</p><h6 id="options-for-has_many-:autosave">4.3.2.2 <code>:autosave</code>
1467
- </h6><p>If you set the <code>:autosave</code> option to <code>true</code>, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.</p><h6 id="options-for-has_many-:class_name">4.3.2.3 <code>:class_name</code>
1468
- </h6><p>If the name of the other model cannot be derived from the association name, you can use the <code>:class_name</code> option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is <code>Transaction</code>, you'd set things up this way:</p><div class="code_container">
1469
- <pre class="brush: ruby; gutter: false; toolbar: false">
1470
- class Customer &lt; ActiveRecord::Base
1471
- has_many :orders, class_name: "Transaction"
1472
- end
1473
-
1474
- </pre>
1475
- </div>
1476
- <h6 id=":dependent">4.3.2.4 <code>:dependent</code>
1477
- </h6><p>Controls what happens to the associated objects when their owner is destroyed:</p>
1478
- <ul>
1479
- <li>
1480
- <code>:destroy</code> causes all the associated objects to also be destroyed</li>
1481
- <li>
1482
- <code>:delete_all</code> causes all the associated objects to be deleted directly from the database (so callbacks will not execute)</li>
1483
- <li>
1484
- <code>:nullify</code> causes the foreign keys to be set to <code>NULL</code>. Callbacks are not executed.</li>
1485
- <li>
1486
- <code>:restrict_with_exception</code> causes an exception to be raised if there are any associated records</li>
1487
- <li>
1488
- <code>:restrict_with_error</code> causes an error to be added to the owner if there are any associated objects</li>
1489
- </ul>
1490
- <div class="note"><p>This option is ignored when you use the <code>:through</code> option on the association.</p></div><h6 id="options-for-has_many-:foreign_key">4.3.2.5 <code>:foreign_key</code>
1491
- </h6><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 <code>_id</code> added. The <code>:foreign_key</code> option lets you set the name of the foreign key directly:</p><div class="code_container">
1492
- <pre class="brush: ruby; gutter: false; toolbar: false">
1493
- class Customer &lt; ActiveRecord::Base
1494
- has_many :orders, foreign_key: "cust_id"
1495
- end
1496
-
1497
- </pre>
1498
- </div>
1499
- <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><h6 id=":inverse_of">4.3.2.6 <code>:inverse_of</code>
1500
- </h6><p>The <code>:inverse_of</code> option specifies the name of the <code>belongs_to</code> association that is the inverse of this association. Does not work in combination with the <code>:through</code> or <code>:as</code> options.</p><div class="code_container">
1501
- <pre class="brush: ruby; gutter: false; toolbar: false">
1502
- class Customer &lt; ActiveRecord::Base
1503
- has_many :orders, inverse_of: :customer
1504
- end
1505
-
1506
- class Order &lt; ActiveRecord::Base
1507
- belongs_to :customer, inverse_of: :orders
1508
- end
1509
-
1510
- </pre>
1511
- </div>
1512
- <h6 id="options-for-has_many-:primary_key">4.3.2.7 <code>:primary_key</code>
1513
- </h6><p>By convention, Rails assumes that the column used to hold the primary key of the association is <code>id</code>. You can override this and explicitly specify the primary key with the <code>:primary_key</code> option.</p><p>Let's say that <code>users</code> table has <code>id</code> as the primary_key but it also has
1514
- <code>guid</code> column. And the requirement is that <code>todos</code> table should hold
1515
- <code>guid</code> column value and not <code>id</code> value. This can be achieved like this</p><div class="code_container">
1516
- <pre class="brush: ruby; gutter: false; toolbar: false">
1517
- class User &lt; ActiveRecord::Base
1518
- has_many :todos, primary_key: :guid
1519
- end
1520
-
1521
- </pre>
1522
- </div>
1523
- <p>Now if we execute <code>@user.todos.create</code> then <code>@todo</code> record will have
1524
- <code>user_id</code> value as the <code>guid</code> value of <code>@user</code>.</p><h6 id="options-for-has_many-:source">4.3.2.8 <code>:source</code>
1525
- </h6><p>The <code>:source</code> option specifies the source association name for a <code>has_many :through</code> association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.</p><h6 id="options-for-has_many-:source_type">4.3.2.9 <code>:source_type</code>
1526
- </h6><p>The <code>:source_type</code> option specifies the source association type for a <code>has_many :through</code> association that proceeds through a polymorphic association.</p><h6 id="options-for-has_many-:through">4.3.2.10 <code>:through</code>
1527
- </h6><p>The <code>:through</code> option specifies a join model through which to perform the query. <code>has_many :through</code> 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><h6 id="options-for-has_many-:validate">4.3.2.11 <code>:validate</code>
1528
- </h6><p>If you set the <code>:validate</code> option to <code>false</code>, then associated objects will not be validated whenever you save this object. By default, this is <code>true</code>: associated objects will be validated when this object is saved.</p><h5 id="scopes-for-has_many">4.3.3 Scopes for <code>has_many</code>
1529
- </h5><p>There may be times when you wish to customize the query used by <code>has_many</code>. Such customizations can be achieved via a scope block. For example:</p><div class="code_container">
1530
- <pre class="brush: ruby; gutter: false; toolbar: false">
1531
- class Customer &lt; ActiveRecord::Base
1532
- has_many :orders, -&gt; { where processed: true }
1533
- end
1534
-
1535
- </pre>
1536
- </div>
1537
- <p>You can use any of the standard <a href="active_record_querying.html">querying methods</a> inside the scope block. The following ones are discussed below:</p>
1538
- <ul>
1539
- <li><code>where</code></li>
1540
- <li><code>extending</code></li>
1541
- <li><code>group</code></li>
1542
- <li><code>includes</code></li>
1543
- <li><code>limit</code></li>
1544
- <li><code>offset</code></li>
1545
- <li><code>order</code></li>
1546
- <li><code>readonly</code></li>
1547
- <li><code>select</code></li>
1548
- <li><code>uniq</code></li>
1549
- </ul>
1550
- <h6 id="scopes-for-has_many-where">4.3.3.1 <code>where</code>
1551
- </h6><p>The <code>where</code> method lets you specify the conditions that the associated object must meet.</p><div class="code_container">
1552
- <pre class="brush: ruby; gutter: false; toolbar: false">
1553
- class Customer &lt; ActiveRecord::Base
1554
- has_many :confirmed_orders, -&gt; { where "confirmed = 1" },
1555
- class_name: "Order"
1556
- end
1557
-
1558
- </pre>
1559
- </div>
1560
- <p>You can also set conditions via a hash:</p><div class="code_container">
1561
- <pre class="brush: ruby; gutter: false; toolbar: false">
1562
- class Customer &lt; ActiveRecord::Base
1563
- has_many :confirmed_orders, -&gt; { where confirmed: true },
1564
- class_name: "Order"
1565
- end
1566
-
1567
- </pre>
1568
- </div>
1569
- <p>If you use a hash-style <code>where</code> option, then record creation via this association will be automatically scoped using the hash. In this case, using <code>@customer.confirmed_orders.create</code> or <code>@customer.confirmed_orders.build</code> will create orders where the confirmed column has the value <code>true</code>.</p><h6 id="scopes-for-has_many-extending">4.3.3.2 <code>extending</code>
1570
- </h6><p>The <code>extending</code> method 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><h6 id="scopes-for-has_many-group">4.3.3.3 <code>group</code>
1571
- </h6><p>The <code>group</code> method supplies an attribute name to group the result set by, using a <code>GROUP BY</code> clause in the finder SQL.</p><div class="code_container">
1572
- <pre class="brush: ruby; gutter: false; toolbar: false">
1573
- class Customer &lt; ActiveRecord::Base
1574
- has_many :line_items, -&gt; { group 'orders.id' },
1575
- through: :orders
1576
- end
1577
-
1578
- </pre>
1579
- </div>
1580
- <h6 id="scopes-for-has_many-includes">4.3.3.4 <code>includes</code>
1581
- </h6><p>You can use the <code>includes</code> method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p><div class="code_container">
1582
- <pre class="brush: ruby; gutter: false; toolbar: false">
1583
- class Customer &lt; ActiveRecord::Base
1584
- has_many :orders
1585
- end
1586
-
1587
- class Order &lt; ActiveRecord::Base
1588
- belongs_to :customer
1589
- has_many :line_items
1590
- end
1591
-
1592
- class LineItem &lt; ActiveRecord::Base
1593
- belongs_to :order
1594
- end
1595
-
1596
- </pre>
1597
- </div>
1598
- <p>If you frequently retrieve line items directly from customers (<code>@customer.orders.line_items</code>), then you can make your code somewhat more efficient by including line items in the association from customers to orders:</p><div class="code_container">
1599
- <pre class="brush: ruby; gutter: false; toolbar: false">
1600
- class Customer &lt; ActiveRecord::Base
1601
- has_many :orders, -&gt; { includes :line_items }
1602
- end
1603
-
1604
- class Order &lt; ActiveRecord::Base
1605
- belongs_to :customer
1606
- has_many :line_items
1607
- end
1608
-
1609
- class LineItem &lt; ActiveRecord::Base
1610
- belongs_to :order
1611
- end
1612
-
1613
- </pre>
1614
- </div>
1615
- <h6 id="scopes-for-has_many-limit">4.3.3.5 <code>limit</code>
1616
- </h6><p>The <code>limit</code> method lets you restrict the total number of objects that will be fetched through an association.</p><div class="code_container">
1617
- <pre class="brush: ruby; gutter: false; toolbar: false">
1618
- class Customer &lt; ActiveRecord::Base
1619
- has_many :recent_orders,
1620
- -&gt; { order('order_date desc').limit(100) },
1621
- class_name: "Order",
1622
- end
1623
-
1624
- </pre>
1625
- </div>
1626
- <h6 id="scopes-for-has_many-offset">4.3.3.6 <code>offset</code>
1627
- </h6><p>The <code>offset</code> method lets you specify the starting offset for fetching objects via an association. For example, <code>-&gt; { offset(11) }</code> will skip the first 11 records.</p><h6 id="scopes-for-has_many-order">4.3.3.7 <code>order</code>
1628
- </h6><p>The <code>order</code> method dictates the order in which associated objects will be received (in the syntax used by an SQL <code>ORDER BY</code> clause).</p><div class="code_container">
1629
- <pre class="brush: ruby; gutter: false; toolbar: false">
1630
- class Customer &lt; ActiveRecord::Base
1631
- has_many :orders, -&gt; { order "date_confirmed DESC" }
1632
- end
1633
-
1634
- </pre>
1635
- </div>
1636
- <h6 id="scopes-for-has_many-readonly">4.3.3.8 <code>readonly</code>
1637
- </h6><p>If you use the <code>readonly</code> method, then the associated objects will be read-only when retrieved via the association.</p><h6 id="scopes-for-has_many-select">4.3.3.9 <code>select</code>
1638
- </h6><p>The <code>select</code> method lets you override the SQL <code>SELECT</code> clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.</p><div class="warning"><p>If you specify your own <code>select</code>, 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><h6 id="distinct">4.3.3.10 <code>distinct</code>
1639
- </h6><p>Use the <code>distinct</code> method to keep the collection free of duplicates. This is
1640
- mostly useful together with the <code>:through</code> option.</p><div class="code_container">
1641
- <pre class="brush: ruby; gutter: false; toolbar: false">
1642
- class Person &lt; ActiveRecord::Base
1643
- has_many :readings
1644
- has_many :articles, through: :readings
1645
- end
1646
-
1647
- person = Person.create(name: 'John')
1648
- article = Article.create(name: 'a1')
1649
- person.articles &lt;&lt; article
1650
- person.articles &lt;&lt; article
1651
- person.articles.inspect # =&gt; [#&lt;Article id: 5, name: "a1"&gt;, #&lt;Article id: 5, name: "a1"&gt;]
1652
- Reading.all.inspect # =&gt; [#&lt;Reading id: 12, person_id: 5, article_id: 5&gt;, #&lt;Reading id: 13, person_id: 5, article_id: 5&gt;]
1653
-
1654
- </pre>
1655
- </div>
1656
- <p>In the above case there are two readings and <code>person.articles</code> brings out both of
1657
- them even though these records are pointing to the same article.</p><p>Now let's set <code>distinct</code>:</p><div class="code_container">
1658
- <pre class="brush: ruby; gutter: false; toolbar: false">
1659
- class Person
1660
- has_many :readings
1661
- has_many :articles, -&gt; { distinct }, through: :readings
1662
- end
1663
-
1664
- person = Person.create(name: 'Honda')
1665
- article = Article.create(name: 'a1')
1666
- person.articles &lt;&lt; article
1667
- person.articles &lt;&lt; article
1668
- person.articles.inspect # =&gt; [#&lt;Article id: 7, name: "a1"&gt;]
1669
- Reading.all.inspect # =&gt; [#&lt;Reading id: 16, person_id: 7, article_id: 7&gt;, #&lt;Reading id: 17, person_id: 7, article_id: 7&gt;]
1670
-
1671
- </pre>
1672
- </div>
1673
- <p>In the above case there are still two readings. However <code>person.articles</code> shows
1674
- only one article because the collection loads only unique records.</p><p>If you want to make sure that, upon insertion, all of the records in the
1675
- persisted association are distinct (so that you can be sure that when you
1676
- inspect the association that you will never find duplicate records), you should
1677
- add a unique index on the table itself. For example, if you have a table named
1678
- <code>person_articles</code> and you want to make sure all the articles are unique, you could
1679
- add the following in a migration:</p><div class="code_container">
1680
- <pre class="brush: ruby; gutter: false; toolbar: false">
1681
- add_index :person_articles, :article, unique: true
1682
-
1683
- </pre>
1684
- </div>
1685
- <p>Note that checking for uniqueness using something like <code>include?</code> is subject
1686
- to race conditions. Do not attempt to use <code>include?</code> to enforce distinctness
1687
- in an association. For instance, using the article example from above, the
1688
- following code would be racy because multiple users could be attempting this
1689
- at the same time:</p><div class="code_container">
1690
- <pre class="brush: ruby; gutter: false; toolbar: false">
1691
- person.articles &lt;&lt; article unless person.articles.include?(article)
1692
-
1693
- </pre>
1694
- </div>
1695
- <h5 id="has_many-association-reference-when-are-objects-saved-questionmark">4.3.4 When are Objects Saved?</h5><p>When you assign an object to a <code>has_many</code> 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><p>If any of these saves fails due to validation errors, then the assignment statement returns <code>false</code> and the assignment itself is cancelled.</p><p>If the parent object (the one declaring the <code>has_many</code> association) is unsaved (that is, <code>new_record?</code> returns <code>true</code>) 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><p>If you want to assign an object to a <code>has_many</code> association without saving the object, use the <code>collection.build</code> method.</p><h4 id="has_and_belongs_to_many-association-reference">4.4 <code>has_and_belongs_to_many</code> Association Reference</h4><p>The <code>has_and_belongs_to_many</code> 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><h5 id="methods-added-by-has_and_belongs_to_many">4.4.1 Methods Added by <code>has_and_belongs_to_many</code>
1696
- </h5><p>When you declare a <code>has_and_belongs_to_many</code> association, the declaring class automatically gains 16 methods related to the association:</p>
1697
- <ul>
1698
- <li><code>collection(force_reload = false)</code></li>
1699
- <li><code>collection&lt;&lt;(object, ...)</code></li>
1700
- <li><code>collection.delete(object, ...)</code></li>
1701
- <li><code>collection.destroy(object, ...)</code></li>
1702
- <li><code>collection=objects</code></li>
1703
- <li><code>collection_singular_ids</code></li>
1704
- <li><code>collection_singular_ids=ids</code></li>
1705
- <li><code>collection.clear</code></li>
1706
- <li><code>collection.empty?</code></li>
1707
- <li><code>collection.size</code></li>
1708
- <li><code>collection.find(...)</code></li>
1709
- <li><code>collection.where(...)</code></li>
1710
- <li><code>collection.exists?(...)</code></li>
1711
- <li><code>collection.build(attributes = {})</code></li>
1712
- <li><code>collection.create(attributes = {})</code></li>
1713
- <li><code>collection.create!(attributes = {})</code></li>
1714
- </ul>
1715
- <p>In all of these methods, <code>collection</code> is replaced with the symbol passed as the first argument to <code>has_and_belongs_to_many</code>, and <code>collection_singular</code> is replaced with the singularized version of that symbol. For example, given the declaration:</p><div class="code_container">
1716
- <pre class="brush: ruby; gutter: false; toolbar: false">
1717
- class Part &lt; ActiveRecord::Base
1718
- has_and_belongs_to_many :assemblies
1719
- end
1720
-
1721
- </pre>
1722
- </div>
1723
- <p>Each instance of the part model will have these methods:</p><div class="code_container">
1724
- <pre class="brush: ruby; gutter: false; toolbar: false">
1725
- assemblies(force_reload = false)
1726
- assemblies&lt;&lt;(object, ...)
1727
- assemblies.delete(object, ...)
1728
- assemblies.destroy(object, ...)
1729
- assemblies=objects
1730
- assembly_ids
1731
- assembly_ids=ids
1732
- assemblies.clear
1733
- assemblies.empty?
1734
- assemblies.size
1735
- assemblies.find(...)
1736
- assemblies.where(...)
1737
- assemblies.exists?(...)
1738
- assemblies.build(attributes = {}, ...)
1739
- assemblies.create(attributes = {})
1740
- assemblies.create!(attributes = {})
1741
-
1742
- </pre>
1743
- </div>
1744
- <h6 id="additional-column-methods">4.4.1.1 Additional Column Methods</h6><p>If the join table for a <code>has_and_belongs_to_many</code> association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.</p><div class="warning"><p>The use of extra attributes on the join table in a <code>has_and_belongs_to_many</code> 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 <code>has_many :through</code> association instead of <code>has_and_belongs_to_many</code>.</p></div><h6 id="methods-added-by-has_and_belongs_to_many-collection(force_reload-=-false)">4.4.1.2 <code>collection(force_reload = false)</code>
1745
- </h6><p>The <code>collection</code> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.</p><div class="code_container">
1746
- <pre class="brush: ruby; gutter: false; toolbar: false">
1747
- @assemblies = @part.assemblies
1748
-
1749
- </pre>
1750
- </div>
1751
- <h6 id="methods-added-by-has_and_belongs_to_many-collection&lt;&lt;(object,-...)">4.4.1.3 <code>collection&lt;&lt;(object, ...)</code>
1752
- </h6><p>The <code>collection&lt;&lt;</code> method adds one or more objects to the collection by creating records in the join table.</p><div class="code_container">
1753
- <pre class="brush: ruby; gutter: false; toolbar: false">
1754
- @part.assemblies &lt;&lt; @assembly1
1755
-
1756
- </pre>
1757
- </div>
1758
- <div class="note"><p>This method is aliased as <code>collection.concat</code> and <code>collection.push</code>.</p></div><h6 id="methods-added-by-has_and_belongs_to_many-collection.delete(object,-...)">4.4.1.4 <code>collection.delete(object, ...)</code>
1759
- </h6><p>The <code>collection.delete</code> method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.</p><div class="code_container">
1760
- <pre class="brush: ruby; gutter: false; toolbar: false">
1761
- @part.assemblies.delete(@assembly1)
1762
-
1763
- </pre>
1764
- </div>
1765
- <div class="warning"><p>This does not trigger callbacks on the join records.</p></div><h6 id="methods-added-by-has_and_belongs_to_many-collection.destroy(object,-...)">4.4.1.5 <code>collection.destroy(object, ...)</code>
1766
- </h6><p>The <code>collection.destroy</code> method removes one or more objects from the collection by running <code>destroy</code> on each record in the join table, including running callbacks. This does not destroy the objects.</p><div class="code_container">
1767
- <pre class="brush: ruby; gutter: false; toolbar: false">
1768
- @part.assemblies.destroy(@assembly1)
1769
-
1770
- </pre>
1771
- </div>
1772
- <h6 id="methods-added-by-has_and_belongs_to_many-collection=objects">4.4.1.6 <code>collection=objects</code>
1773
- </h6><p>The <code>collection=</code> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.</p><h6 id="methods-added-by-has_and_belongs_to_many-collection_singular_ids">4.4.1.7 <code>collection_singular_ids</code>
1774
- </h6><p>The <code>collection_singular_ids</code> method returns an array of the ids of the objects in the collection.</p><div class="code_container">
1775
- <pre class="brush: ruby; gutter: false; toolbar: false">
1776
- @assembly_ids = @part.assembly_ids
1777
-
1778
- </pre>
1779
- </div>
1780
- <h6 id="methods-added-by-has_and_belongs_to_many-collection_singular_ids=ids">4.4.1.8 <code>collection_singular_ids=ids</code>
1781
- </h6><p>The <code>collection_singular_ids=</code> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.</p><h6 id="methods-added-by-has_and_belongs_to_many-collection.clear">4.4.1.9 <code>collection.clear</code>
1782
- </h6><p>The <code>collection.clear</code> method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.</p><h6 id="methods-added-by-has_and_belongs_to_many-collection.empty-questionmark">4.4.1.10 <code>collection.empty?</code>
1783
- </h6><p>The <code>collection.empty?</code> method returns <code>true</code> if the collection does not contain any associated objects.</p><div class="code_container">
1784
- <pre class="brush: ruby; gutter: false; toolbar: false">
1785
- &lt;% if @part.assemblies.empty? %&gt;
1786
- This part is not used in any assemblies
1787
- &lt;% end %&gt;
1788
-
1789
- </pre>
1790
- </div>
1791
- <h6 id="methods-added-by-has_and_belongs_to_many-collection.size">4.4.1.11 <code>collection.size</code>
1792
- </h6><p>The <code>collection.size</code> method returns the number of objects in the collection.</p><div class="code_container">
1793
- <pre class="brush: ruby; gutter: false; toolbar: false">
1794
- @assembly_count = @part.assemblies.size
1795
-
1796
- </pre>
1797
- </div>
1798
- <h6 id="methods-added-by-has_and_belongs_to_many-collection.find(...)">4.4.1.12 <code>collection.find(...)</code>
1799
- </h6><p>The <code>collection.find</code> method finds objects within the collection. It uses the same syntax and options as <code>ActiveRecord::Base.find</code>. It also adds the additional condition that the object must be in the collection.</p><div class="code_container">
1800
- <pre class="brush: ruby; gutter: false; toolbar: false">
1801
- @assembly = @part.assemblies.find(1)
1802
-
1803
- </pre>
1804
- </div>
1805
- <h6 id="methods-added-by-has_and_belongs_to_many-collection.where(...)">4.4.1.13 <code>collection.where(...)</code>
1806
- </h6><p>The <code>collection.where</code> 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><div class="code_container">
1807
- <pre class="brush: ruby; gutter: false; toolbar: false">
1808
- @new_assemblies = @part.assemblies.where("created_at &gt; ?", 2.days.ago)
1809
-
1810
- </pre>
1811
- </div>
1812
- <h6 id="methods-added-by-has_and_belongs_to_many-collection.exists-questionmark(...)">4.4.1.14 <code>collection.exists?(...)</code>
1813
- </h6><p>The <code>collection.exists?</code> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as <code>ActiveRecord::Base.exists?</code>.</p><h6 id="collection.build(attributes-=-{})">4.4.1.15 <code>collection.build(attributes = {})</code>
1814
- </h6><p>The <code>collection.build</code> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will <em>not</em> yet be saved.</p><div class="code_container">
1815
- <pre class="brush: ruby; gutter: false; toolbar: false">
1816
- @assembly = @part.assemblies.build({assembly_name: "Transmission housing"})
1817
-
1818
- </pre>
1819
- </div>
1820
- <h6 id="methods-added-by-has_and_belongs_to_many-collection.create(attributes-=-{})">4.4.1.16 <code>collection.create(attributes = {})</code>
1821
- </h6><p>The <code>collection.create</code> 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><div class="code_container">
1822
- <pre class="brush: ruby; gutter: false; toolbar: false">
1823
- @assembly = @part.assemblies.create({assembly_name: "Transmission housing"})
1824
-
1825
- </pre>
1826
- </div>
1827
- <h6 id="methods-added-by-has_and_belongs_to_many-collection.create-bang(attributes-=-{})">4.4.1.17 <code>collection.create!(attributes = {})</code>
1828
- </h6><p>Does the same as <code>collection.create</code>, but raises <code>ActiveRecord::RecordInvalid</code> if the record is invalid.</p><h5 id="options-for-has_and_belongs_to_many">4.4.2 Options for <code>has_and_belongs_to_many</code>
1829
- </h5><p>While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the <code>has_and_belongs_to_many</code> association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:</p><div class="code_container">
1830
- <pre class="brush: ruby; gutter: false; toolbar: false">
1831
- class Parts &lt; ActiveRecord::Base
1832
- has_and_belongs_to_many :assemblies, autosave: true,
1833
- readonly: true
1834
- end
1835
-
1836
- </pre>
1837
- </div>
1838
- <p>The <code>has_and_belongs_to_many</code> association supports these options:</p>
1839
- <ul>
1840
- <li><code>:association_foreign_key</code></li>
1841
- <li><code>:autosave</code></li>
1842
- <li><code>:class_name</code></li>
1843
- <li><code>:foreign_key</code></li>
1844
- <li><code>:join_table</code></li>
1845
- <li><code>:validate</code></li>
1846
- <li><code>:readonly</code></li>
1847
- </ul>
1848
- <h6 id=":association_foreign_key">4.4.2.1 <code>:association_foreign_key</code>
1849
- </h6><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 <code>_id</code> added. The <code>:association_foreign_key</code> option lets you set the name of the foreign key directly:</p><div class="info"><p>The <code>:foreign_key</code> and <code>:association_foreign_key</code> options are useful when setting up a many-to-many self-join. For example:</p></div><div class="code_container">
1850
- <pre class="brush: ruby; gutter: false; toolbar: false">
1851
- class User &lt; ActiveRecord::Base
1852
- has_and_belongs_to_many :friends,
1853
- class_name: "User",
1854
- foreign_key: "this_user_id",
1855
- association_foreign_key: "other_user_id"
1856
- end
1857
-
1858
- </pre>
1859
- </div>
1860
- <h6 id="options-for-has_and_belongs_to_many-:autosave">4.4.2.2 <code>:autosave</code>
1861
- </h6><p>If you set the <code>:autosave</code> option to <code>true</code>, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.</p><h6 id="options-for-has_and_belongs_to_many-:class_name">4.4.2.3 <code>:class_name</code>
1862
- </h6><p>If the name of the other model cannot be derived from the association name, you can use the <code>:class_name</code> option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is <code>Gadget</code>, you'd set things up this way:</p><div class="code_container">
1863
- <pre class="brush: ruby; gutter: false; toolbar: false">
1864
- class Parts &lt; ActiveRecord::Base
1865
- has_and_belongs_to_many :assemblies, class_name: "Gadget"
1866
- end
1867
-
1868
- </pre>
1869
- </div>
1870
- <h6 id="options-for-has_and_belongs_to_many-:foreign_key">4.4.2.4 <code>:foreign_key</code>
1871
- </h6><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 <code>_id</code> added. The <code>:foreign_key</code> option lets you set the name of the foreign key directly:</p><div class="code_container">
1872
- <pre class="brush: ruby; gutter: false; toolbar: false">
1873
- class User &lt; ActiveRecord::Base
1874
- has_and_belongs_to_many :friends,
1875
- class_name: "User",
1876
- foreign_key: "this_user_id",
1877
- association_foreign_key: "other_user_id"
1878
- end
1879
-
1880
- </pre>
1881
- </div>
1882
- <h6 id=":join_table">4.4.2.5 <code>:join_table</code>
1883
- </h6><p>If the default name of the join table, based on lexical ordering, is not what you want, you can use the <code>:join_table</code> option to override the default.</p><h6 id="options-for-has_and_belongs_to_many-:validate">4.4.2.6 <code>:validate</code>
1884
- </h6><p>If you set the <code>:validate</code> option to <code>false</code>, then associated objects will not be validated whenever you save this object. By default, this is <code>true</code>: associated objects will be validated when this object is saved.</p><h5 id="scopes-for-has_and_belongs_to_many">4.4.3 Scopes for <code>has_and_belongs_to_many</code>
1885
- </h5><p>There may be times when you wish to customize the query used by <code>has_and_belongs_to_many</code>. Such customizations can be achieved via a scope block. For example:</p><div class="code_container">
1886
- <pre class="brush: ruby; gutter: false; toolbar: false">
1887
- class Parts &lt; ActiveRecord::Base
1888
- has_and_belongs_to_many :assemblies, -&gt; { where active: true }
1889
- end
1890
-
1891
- </pre>
1892
- </div>
1893
- <p>You can use any of the standard <a href="active_record_querying.html">querying methods</a> inside the scope block. The following ones are discussed below:</p>
1894
- <ul>
1895
- <li><code>where</code></li>
1896
- <li><code>extending</code></li>
1897
- <li><code>group</code></li>
1898
- <li><code>includes</code></li>
1899
- <li><code>limit</code></li>
1900
- <li><code>offset</code></li>
1901
- <li><code>order</code></li>
1902
- <li><code>readonly</code></li>
1903
- <li><code>select</code></li>
1904
- <li><code>uniq</code></li>
1905
- </ul>
1906
- <h6 id="scopes-for-has_and_belongs_to_many-where">4.4.3.1 <code>where</code>
1907
- </h6><p>The <code>where</code> method lets you specify the conditions that the associated object must meet.</p><div class="code_container">
1908
- <pre class="brush: ruby; gutter: false; toolbar: false">
1909
- class Parts &lt; ActiveRecord::Base
1910
- has_and_belongs_to_many :assemblies,
1911
- -&gt; { where "factory = 'Seattle'" }
1912
- end
1913
-
1914
- </pre>
1915
- </div>
1916
- <p>You can also set conditions via a hash:</p><div class="code_container">
1917
- <pre class="brush: ruby; gutter: false; toolbar: false">
1918
- class Parts &lt; ActiveRecord::Base
1919
- has_and_belongs_to_many :assemblies,
1920
- -&gt; { where factory: 'Seattle' }
1921
- end
1922
-
1923
- </pre>
1924
- </div>
1925
- <p>If you use a hash-style <code>where</code>, then record creation via this association will be automatically scoped using the hash. In this case, using <code>@parts.assemblies.create</code> or <code>@parts.assemblies.build</code> will create orders where the <code>factory</code> column has the value "Seattle".</p><h6 id="scopes-for-has_and_belongs_to_many-extending">4.4.3.2 <code>extending</code>
1926
- </h6><p>The <code>extending</code> method 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><h6 id="scopes-for-has_and_belongs_to_many-group">4.4.3.3 <code>group</code>
1927
- </h6><p>The <code>group</code> method supplies an attribute name to group the result set by, using a <code>GROUP BY</code> clause in the finder SQL.</p><div class="code_container">
1928
- <pre class="brush: ruby; gutter: false; toolbar: false">
1929
- class Parts &lt; ActiveRecord::Base
1930
- has_and_belongs_to_many :assemblies, -&gt; { group "factory" }
1931
- end
1932
-
1933
- </pre>
1934
- </div>
1935
- <h6 id="scopes-for-has_and_belongs_to_many-includes">4.4.3.4 <code>includes</code>
1936
- </h6><p>You can use the <code>includes</code> method to specify second-order associations that should be eager-loaded when this association is used.</p><h6 id="scopes-for-has_and_belongs_to_many-limit">4.4.3.5 <code>limit</code>
1937
- </h6><p>The <code>limit</code> method lets you restrict the total number of objects that will be fetched through an association.</p><div class="code_container">
1938
- <pre class="brush: ruby; gutter: false; toolbar: false">
1939
- class Parts &lt; ActiveRecord::Base
1940
- has_and_belongs_to_many :assemblies,
1941
- -&gt; { order("created_at DESC").limit(50) }
1942
- end
1943
-
1944
- </pre>
1945
- </div>
1946
- <h6 id="scopes-for-has_and_belongs_to_many-offset">4.4.3.6 <code>offset</code>
1947
- </h6><p>The <code>offset</code> method lets you specify the starting offset for fetching objects via an association. For example, if you set <code>offset(11)</code>, it will skip the first 11 records.</p><h6 id="scopes-for-has_and_belongs_to_many-order">4.4.3.7 <code>order</code>
1948
- </h6><p>The <code>order</code> method dictates the order in which associated objects will be received (in the syntax used by an SQL <code>ORDER BY</code> clause).</p><div class="code_container">
1949
- <pre class="brush: ruby; gutter: false; toolbar: false">
1950
- class Parts &lt; ActiveRecord::Base
1951
- has_and_belongs_to_many :assemblies,
1952
- -&gt; { order "assembly_name ASC" }
1953
- end
1954
-
1955
- </pre>
1956
- </div>
1957
- <h6 id="scopes-for-has_and_belongs_to_many-readonly">4.4.3.8 <code>readonly</code>
1958
- </h6><p>If you use the <code>readonly</code> method, then the associated objects will be read-only when retrieved via the association.</p><h6 id="scopes-for-has_and_belongs_to_many-select">4.4.3.9 <code>select</code>
1959
- </h6><p>The <code>select</code> method lets you override the SQL <code>SELECT</code> clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.</p><h6 id="uniq">4.4.3.10 <code>uniq</code>
1960
- </h6><p>Use the <code>uniq</code> method to remove duplicates from the collection.</p><h5 id="has_and_belongs_to_many-association-reference-when-are-objects-saved-questionmark">4.4.4 When are Objects Saved?</h5><p>When you assign an object to a <code>has_and_belongs_to_many</code> 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><p>If any of these saves fails due to validation errors, then the assignment statement returns <code>false</code> and the assignment itself is cancelled.</p><p>If the parent object (the one declaring the <code>has_and_belongs_to_many</code> association) is unsaved (that is, <code>new_record?</code> returns <code>true</code>) 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><p>If you want to assign an object to a <code>has_and_belongs_to_many</code> association without saving the object, use the <code>collection.build</code> method.</p><h4 id="association-callbacks">4.5 Association Callbacks</h4><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 <code>:before_save</code> callback to cause something to happen just before an object is saved.</p><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>
1961
- <ul>
1962
- <li><code>before_add</code></li>
1963
- <li><code>after_add</code></li>
1964
- <li><code>before_remove</code></li>
1965
- <li><code>after_remove</code></li>
1966
- </ul>
1967
- <p>You define association callbacks by adding options to the association declaration. For example:</p><div class="code_container">
1968
- <pre class="brush: ruby; gutter: false; toolbar: false">
1969
- class Customer &lt; ActiveRecord::Base
1970
- has_many :orders, before_add: :check_credit_limit
1971
-
1972
- def check_credit_limit(order)
1973
- ...
1974
- end
1975
- end
1976
-
1977
- </pre>
1978
- </div>
1979
- <p>Rails passes the object being added or removed to the callback.</p><p>You can stack callbacks on a single event by passing them as an array:</p><div class="code_container">
1980
- <pre class="brush: ruby; gutter: false; toolbar: false">
1981
- class Customer &lt; ActiveRecord::Base
1982
- has_many :orders,
1983
- before_add: [:check_credit_limit, :calculate_shipping_charges]
1984
-
1985
- def check_credit_limit(order)
1986
- ...
1987
- end
1988
-
1989
- def calculate_shipping_charges(order)
1990
- ...
1991
- end
1992
- end
1993
-
1994
- </pre>
1995
- </div>
1996
- <p>If a <code>before_add</code> callback throws an exception, the object does not get added to the collection. Similarly, if a <code>before_remove</code> callback throws an exception, the object does not get removed from the collection.</p><h4 id="association-extensions">4.6 Association Extensions</h4><p>You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:</p><div class="code_container">
1997
- <pre class="brush: ruby; gutter: false; toolbar: false">
1998
- class Customer &lt; ActiveRecord::Base
1999
- has_many :orders do
2000
- def find_by_order_prefix(order_number)
2001
- find_by(region_id: order_number[0..2])
2002
- end
2003
- end
2004
- end
2005
-
2006
- </pre>
2007
- </div>
2008
- <p>If you have an extension that should be shared by many associations, you can use a named extension module. For example:</p><div class="code_container">
2009
- <pre class="brush: ruby; gutter: false; toolbar: false">
2010
- module FindRecentExtension
2011
- def find_recent
2012
- where("created_at &gt; ?", 5.days.ago)
2013
- end
2014
- end
2015
-
2016
- class Customer &lt; ActiveRecord::Base
2017
- has_many :orders, -&gt; { extending FindRecentExtension }
2018
- end
2019
-
2020
- class Supplier &lt; ActiveRecord::Base
2021
- has_many :deliveries, -&gt; { extending FindRecentExtension }
2022
- end
2023
-
2024
- </pre>
2025
- </div>
2026
- <p>Extensions can refer to the internals of the association proxy using these three attributes of the <code>proxy_association</code> accessor:</p>
2027
- <ul>
2028
- <li>
2029
- <code>proxy_association.owner</code> returns the object that the association is a part of.</li>
2030
- <li>
2031
- <code>proxy_association.reflection</code> returns the reflection object that describes the association.</li>
2032
- <li>
2033
- <code>proxy_association.target</code> returns the associated object for <code>belongs_to</code> or <code>has_one</code>, or the collection of associated objects for <code>has_many</code> or <code>has_and_belongs_to_many</code>.</li>
2034
- </ul>
2035
-
2036
-
2037
- <h3>Feedback</h3>
2038
- <p>
2039
- You're encouraged to help improve the quality of this guide.
2040
- </p>
2041
- <p>
2042
- Please contribute if you see any typos or factual errors.
2043
- To get started, you can read our <a href="http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">documentation contributions</a> section.
2044
- </p>
2045
- <p>
2046
- You may also find incomplete content, or stuff that is not up to date.
2047
- Please do add any missing documentation for master. Make sure to check
2048
- <a href="http://edgeguides.rubyonrails.org">Edge Guides</a> first to verify
2049
- if the issues are already fixed or not on the master branch.
2050
- Check the <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
2051
- for style and conventions.
2052
- </p>
2053
- <p>
2054
- If for whatever reason you spot something to fix but cannot patch it yourself, please
2055
- <a href="https://github.com/rails/rails/issues">open an issue</a>.
2056
- </p>
2057
- <p>And last but not least, any kind of discussion regarding Ruby on Rails
2058
- documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
2059
- </p>
2060
- </div>
2061
- </div>
2062
- </div>
2063
-
2064
- <hr class="hide" />
2065
- <div id="footer">
2066
- <div class="wrapper">
2067
- <p>This work is licensed under a <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International</a> License</p>
2068
- <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
2069
-
2070
- </div>
2071
- </div>
2072
-
2073
- <script type="text/javascript" src="javascripts/jquery.min.js"></script>
2074
- <script type="text/javascript" src="javascripts/responsive-tables.js"></script>
2075
- <script type="text/javascript" src="javascripts/guides.js"></script>
2076
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
2077
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
2078
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
2079
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
2080
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
2081
- <script type="text/javascript">
2082
- SyntaxHighlighter.all();
2083
- $(guidesIndex.bind);
2084
- </script>
2085
- </body>
2086
- </html>