rails 4.2.11.3 → 5.0.7.1

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