rails 3.2.22.5 → 4.0.0.beta1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rails might be problematic. Click here for more details.

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