activerecord 5.0.7 → 5.1.7

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

Potentially problematic release.


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

Files changed (219) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +657 -2080
  3. data/MIT-LICENSE +1 -1
  4. data/README.rdoc +1 -1
  5. data/examples/performance.rb +28 -28
  6. data/examples/simple.rb +3 -3
  7. data/lib/active_record/aggregations.rb +244 -244
  8. data/lib/active_record/association_relation.rb +5 -5
  9. data/lib/active_record/associations/alias_tracker.rb +10 -11
  10. data/lib/active_record/associations/association.rb +23 -5
  11. data/lib/active_record/associations/association_scope.rb +95 -81
  12. data/lib/active_record/associations/belongs_to_association.rb +7 -4
  13. data/lib/active_record/associations/builder/belongs_to.rb +30 -16
  14. data/lib/active_record/associations/builder/collection_association.rb +1 -2
  15. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +27 -27
  16. data/lib/active_record/associations/collection_association.rb +36 -205
  17. data/lib/active_record/associations/collection_proxy.rb +132 -63
  18. data/lib/active_record/associations/has_many_association.rb +10 -19
  19. data/lib/active_record/associations/has_many_through_association.rb +12 -4
  20. data/lib/active_record/associations/has_one_association.rb +24 -28
  21. data/lib/active_record/associations/has_one_through_association.rb +5 -1
  22. data/lib/active_record/associations/join_dependency/join_association.rb +4 -28
  23. data/lib/active_record/associations/join_dependency/join_base.rb +1 -1
  24. data/lib/active_record/associations/join_dependency/join_part.rb +1 -1
  25. data/lib/active_record/associations/join_dependency.rb +121 -118
  26. data/lib/active_record/associations/preloader/association.rb +64 -64
  27. data/lib/active_record/associations/preloader/belongs_to.rb +0 -2
  28. data/lib/active_record/associations/preloader/collection_association.rb +6 -6
  29. data/lib/active_record/associations/preloader/has_many.rb +0 -2
  30. data/lib/active_record/associations/preloader/singular_association.rb +6 -8
  31. data/lib/active_record/associations/preloader/through_association.rb +41 -41
  32. data/lib/active_record/associations/preloader.rb +94 -94
  33. data/lib/active_record/associations/singular_association.rb +8 -25
  34. data/lib/active_record/associations/through_association.rb +2 -5
  35. data/lib/active_record/associations.rb +1591 -1562
  36. data/lib/active_record/attribute/user_provided_default.rb +4 -2
  37. data/lib/active_record/attribute.rb +98 -71
  38. data/lib/active_record/attribute_assignment.rb +61 -61
  39. data/lib/active_record/attribute_decorators.rb +35 -13
  40. data/lib/active_record/attribute_methods/before_type_cast.rb +7 -7
  41. data/lib/active_record/attribute_methods/dirty.rb +229 -46
  42. data/lib/active_record/attribute_methods/primary_key.rb +74 -73
  43. data/lib/active_record/attribute_methods/read.rb +39 -35
  44. data/lib/active_record/attribute_methods/serialization.rb +7 -7
  45. data/lib/active_record/attribute_methods/time_zone_conversion.rb +35 -58
  46. data/lib/active_record/attribute_methods/write.rb +30 -33
  47. data/lib/active_record/attribute_methods.rb +56 -65
  48. data/lib/active_record/attribute_mutation_tracker.rb +63 -11
  49. data/lib/active_record/attribute_set/builder.rb +27 -33
  50. data/lib/active_record/attribute_set/yaml_encoder.rb +41 -0
  51. data/lib/active_record/attribute_set.rb +9 -6
  52. data/lib/active_record/attributes.rb +22 -22
  53. data/lib/active_record/autosave_association.rb +18 -13
  54. data/lib/active_record/base.rb +24 -22
  55. data/lib/active_record/callbacks.rb +56 -14
  56. data/lib/active_record/coders/yaml_column.rb +9 -11
  57. data/lib/active_record/collection_cache_key.rb +3 -4
  58. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +330 -284
  59. data/lib/active_record/connection_adapters/abstract/database_limits.rb +1 -3
  60. data/lib/active_record/connection_adapters/abstract/database_statements.rb +39 -37
  61. data/lib/active_record/connection_adapters/abstract/query_cache.rb +32 -27
  62. data/lib/active_record/connection_adapters/abstract/quoting.rb +62 -51
  63. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +10 -20
  64. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +74 -79
  65. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +53 -41
  66. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +120 -100
  67. data/lib/active_record/connection_adapters/abstract/transaction.rb +49 -43
  68. data/lib/active_record/connection_adapters/abstract_adapter.rb +165 -135
  69. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +404 -424
  70. data/lib/active_record/connection_adapters/column.rb +26 -4
  71. data/lib/active_record/connection_adapters/connection_specification.rb +128 -118
  72. data/lib/active_record/connection_adapters/mysql/column.rb +6 -31
  73. data/lib/active_record/connection_adapters/mysql/database_statements.rb +36 -49
  74. data/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +22 -22
  75. data/lib/active_record/connection_adapters/mysql/quoting.rb +6 -12
  76. data/lib/active_record/connection_adapters/mysql/schema_creation.rb +49 -45
  77. data/lib/active_record/connection_adapters/mysql/schema_definitions.rb +16 -19
  78. data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +54 -28
  79. data/lib/active_record/connection_adapters/mysql/schema_statements.rb +43 -0
  80. data/lib/active_record/connection_adapters/mysql/type_metadata.rb +7 -6
  81. data/lib/active_record/connection_adapters/mysql2_adapter.rb +23 -27
  82. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +32 -53
  83. data/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb +3 -3
  84. data/lib/active_record/connection_adapters/postgresql/oid/array.rb +19 -9
  85. data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +5 -3
  86. data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +1 -1
  87. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +2 -2
  88. data/lib/active_record/connection_adapters/postgresql/oid/decimal.rb +1 -1
  89. data/lib/active_record/connection_adapters/postgresql/oid/enum.rb +3 -3
  90. data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +16 -16
  91. data/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb +0 -10
  92. data/lib/active_record/connection_adapters/postgresql/oid/{rails_5_1_point.rb → legacy_point.rb} +9 -16
  93. data/lib/active_record/connection_adapters/postgresql/oid/money.rb +2 -2
  94. data/lib/active_record/connection_adapters/postgresql/oid/oid.rb +13 -0
  95. data/lib/active_record/connection_adapters/postgresql/oid/point.rb +28 -8
  96. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +32 -30
  97. data/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb +2 -1
  98. data/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +51 -51
  99. data/lib/active_record/connection_adapters/postgresql/oid.rb +22 -21
  100. data/lib/active_record/connection_adapters/postgresql/quoting.rb +40 -35
  101. data/lib/active_record/connection_adapters/postgresql/schema_creation.rb +15 -0
  102. data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +37 -24
  103. data/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +19 -23
  104. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +182 -222
  105. data/lib/active_record/connection_adapters/postgresql/type_metadata.rb +6 -4
  106. data/lib/active_record/connection_adapters/postgresql/utils.rb +7 -5
  107. data/lib/active_record/connection_adapters/postgresql_adapter.rb +198 -167
  108. data/lib/active_record/connection_adapters/schema_cache.rb +16 -7
  109. data/lib/active_record/connection_adapters/sql_type_metadata.rb +3 -3
  110. data/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb +1 -1
  111. data/lib/active_record/connection_adapters/sqlite3/quoting.rb +16 -19
  112. data/lib/active_record/connection_adapters/sqlite3/schema_creation.rb +1 -8
  113. data/lib/active_record/connection_adapters/sqlite3/schema_definitions.rb +28 -0
  114. data/lib/active_record/connection_adapters/sqlite3/schema_dumper.rb +17 -0
  115. data/lib/active_record/connection_adapters/sqlite3/schema_statements.rb +32 -0
  116. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +184 -167
  117. data/lib/active_record/connection_adapters/statement_pool.rb +7 -7
  118. data/lib/active_record/connection_handling.rb +14 -26
  119. data/lib/active_record/core.rb +109 -93
  120. data/lib/active_record/counter_cache.rb +60 -13
  121. data/lib/active_record/define_callbacks.rb +20 -0
  122. data/lib/active_record/dynamic_matchers.rb +80 -79
  123. data/lib/active_record/enum.rb +8 -6
  124. data/lib/active_record/errors.rb +64 -15
  125. data/lib/active_record/explain.rb +1 -2
  126. data/lib/active_record/explain_registry.rb +1 -1
  127. data/lib/active_record/explain_subscriber.rb +7 -4
  128. data/lib/active_record/fixture_set/file.rb +11 -8
  129. data/lib/active_record/fixtures.rb +66 -53
  130. data/lib/active_record/gem_version.rb +1 -1
  131. data/lib/active_record/inheritance.rb +93 -79
  132. data/lib/active_record/integration.rb +7 -7
  133. data/lib/active_record/internal_metadata.rb +3 -16
  134. data/lib/active_record/legacy_yaml_adapter.rb +1 -1
  135. data/lib/active_record/locking/optimistic.rb +69 -74
  136. data/lib/active_record/locking/pessimistic.rb +10 -1
  137. data/lib/active_record/log_subscriber.rb +23 -28
  138. data/lib/active_record/migration/command_recorder.rb +94 -94
  139. data/lib/active_record/migration/compatibility.rb +100 -47
  140. data/lib/active_record/migration/join_table.rb +6 -6
  141. data/lib/active_record/migration.rb +153 -155
  142. data/lib/active_record/model_schema.rb +94 -107
  143. data/lib/active_record/nested_attributes.rb +200 -199
  144. data/lib/active_record/null_relation.rb +11 -34
  145. data/lib/active_record/persistence.rb +65 -50
  146. data/lib/active_record/query_cache.rb +2 -6
  147. data/lib/active_record/querying.rb +3 -4
  148. data/lib/active_record/railtie.rb +16 -17
  149. data/lib/active_record/railties/controller_runtime.rb +6 -2
  150. data/lib/active_record/railties/databases.rake +105 -133
  151. data/lib/active_record/railties/jdbcmysql_error.rb +1 -1
  152. data/lib/active_record/readonly_attributes.rb +2 -2
  153. data/lib/active_record/reflection.rb +154 -108
  154. data/lib/active_record/relation/batches/batch_enumerator.rb +1 -1
  155. data/lib/active_record/relation/batches.rb +80 -51
  156. data/lib/active_record/relation/calculations.rb +169 -162
  157. data/lib/active_record/relation/delegation.rb +32 -31
  158. data/lib/active_record/relation/finder_methods.rb +197 -231
  159. data/lib/active_record/relation/merger.rb +58 -62
  160. data/lib/active_record/relation/predicate_builder/array_handler.rb +7 -5
  161. data/lib/active_record/relation/predicate_builder/association_query_handler.rb +23 -23
  162. data/lib/active_record/relation/predicate_builder/base_handler.rb +3 -1
  163. data/lib/active_record/relation/predicate_builder/basic_object_handler.rb +0 -8
  164. data/lib/active_record/relation/predicate_builder/polymorphic_array_handler.rb +12 -10
  165. data/lib/active_record/relation/predicate_builder/range_handler.rb +0 -8
  166. data/lib/active_record/relation/predicate_builder.rb +92 -89
  167. data/lib/active_record/relation/query_attribute.rb +1 -1
  168. data/lib/active_record/relation/query_methods.rb +255 -293
  169. data/lib/active_record/relation/record_fetch_warning.rb +3 -3
  170. data/lib/active_record/relation/spawn_methods.rb +4 -5
  171. data/lib/active_record/relation/where_clause.rb +80 -65
  172. data/lib/active_record/relation/where_clause_factory.rb +47 -8
  173. data/lib/active_record/relation.rb +93 -119
  174. data/lib/active_record/result.rb +41 -32
  175. data/lib/active_record/runtime_registry.rb +3 -3
  176. data/lib/active_record/sanitization.rb +176 -192
  177. data/lib/active_record/schema.rb +3 -3
  178. data/lib/active_record/schema_dumper.rb +15 -38
  179. data/lib/active_record/schema_migration.rb +8 -4
  180. data/lib/active_record/scoping/default.rb +90 -90
  181. data/lib/active_record/scoping/named.rb +11 -11
  182. data/lib/active_record/scoping.rb +6 -6
  183. data/lib/active_record/secure_token.rb +2 -2
  184. data/lib/active_record/statement_cache.rb +13 -15
  185. data/lib/active_record/store.rb +31 -32
  186. data/lib/active_record/suppressor.rb +2 -1
  187. data/lib/active_record/table_metadata.rb +9 -5
  188. data/lib/active_record/tasks/database_tasks.rb +65 -55
  189. data/lib/active_record/tasks/mysql_database_tasks.rb +76 -73
  190. data/lib/active_record/tasks/postgresql_database_tasks.rb +72 -47
  191. data/lib/active_record/tasks/sqlite_database_tasks.rb +18 -16
  192. data/lib/active_record/timestamp.rb +46 -25
  193. data/lib/active_record/touch_later.rb +1 -2
  194. data/lib/active_record/transactions.rb +97 -109
  195. data/lib/active_record/type/adapter_specific_registry.rb +46 -42
  196. data/lib/active_record/type/decimal_without_scale.rb +13 -0
  197. data/lib/active_record/type/hash_lookup_type_map.rb +3 -3
  198. data/lib/active_record/type/internal/abstract_json.rb +4 -0
  199. data/lib/active_record/type/serialized.rb +14 -8
  200. data/lib/active_record/type/text.rb +9 -0
  201. data/lib/active_record/type/time.rb +0 -1
  202. data/lib/active_record/type/type_map.rb +11 -15
  203. data/lib/active_record/type/unsigned_integer.rb +15 -0
  204. data/lib/active_record/type.rb +17 -13
  205. data/lib/active_record/type_caster/connection.rb +8 -6
  206. data/lib/active_record/type_caster/map.rb +3 -1
  207. data/lib/active_record/type_caster.rb +2 -2
  208. data/lib/active_record/validations/associated.rb +1 -1
  209. data/lib/active_record/validations/presence.rb +2 -2
  210. data/lib/active_record/validations/uniqueness.rb +8 -39
  211. data/lib/active_record/validations.rb +4 -4
  212. data/lib/active_record/version.rb +1 -1
  213. data/lib/active_record.rb +20 -20
  214. data/lib/rails/generators/active_record/migration/migration_generator.rb +37 -34
  215. data/lib/rails/generators/active_record/migration.rb +1 -1
  216. data/lib/rails/generators/active_record/model/model_generator.rb +9 -9
  217. data/lib/rails/generators/active_record.rb +4 -4
  218. metadata +24 -13
  219. data/lib/active_record/relation/predicate_builder/class_handler.rb +0 -27
@@ -1,7 +1,7 @@
1
- require 'active_support/core_ext/enumerable'
2
- require 'active_support/core_ext/string/conversions'
3
- require 'active_support/core_ext/module/remove_method'
4
- require 'active_record/errors'
1
+ require "active_support/core_ext/enumerable"
2
+ require "active_support/core_ext/string/conversions"
3
+ require "active_support/core_ext/module/remove_method"
4
+ require "active_record/errors"
5
5
 
6
6
  module ActiveRecord
7
7
  class AssociationNotFoundError < ConfigurationError #:nodoc:
@@ -90,13 +90,23 @@ module ActiveRecord
90
90
  through_reflection = reflection.through_reflection
91
91
  source_reflection_names = reflection.source_reflection_names
92
92
  source_associations = reflection.through_reflection.klass._reflections.keys
93
- super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?")
93
+ super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(two_words_connector: ' or ', last_word_connector: ', or ', locale: :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ', locale: :en)}?")
94
94
  else
95
95
  super("Could not find the source association(s).")
96
96
  end
97
97
  end
98
98
  end
99
99
 
100
+ class HasManyThroughOrderError < ActiveRecordError #:nodoc:
101
+ def initialize(owner_class_name = nil, reflection = nil, through_reflection = nil)
102
+ if owner_class_name && reflection && through_reflection
103
+ super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through '#{owner_class_name}##{through_reflection.name}' before the through association is defined.")
104
+ else
105
+ super("Cannot have a has_many :through association before the through association is defined.")
106
+ end
107
+ end
108
+ end
109
+
100
110
  class ThroughCantAssociateThroughHasOneOrManyReflection < ActiveRecordError #:nodoc:
101
111
  def initialize(owner = nil, reflection = nil)
102
112
  if owner && reflection
@@ -107,6 +117,21 @@ module ActiveRecord
107
117
  end
108
118
  end
109
119
 
120
+ class AmbiguousSourceReflectionForThroughAssociation < ActiveRecordError # :nodoc:
121
+ def initialize(klass, macro, association_name, options, possible_sources)
122
+ example_options = options.dup
123
+ example_options[:source] = possible_sources.first
124
+
125
+ super("Ambiguous source reflection for through association. Please " \
126
+ "specify a :source directive on your declaration like:\n" \
127
+ "\n" \
128
+ " class #{klass} < ActiveRecord::Base\n" \
129
+ " #{macro} :#{association_name}, #{example_options}\n" \
130
+ " end"
131
+ )
132
+ end
133
+ end
134
+
110
135
  class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ThroughCantAssociateThroughHasOneOrManyReflection #:nodoc:
111
136
  end
112
137
 
@@ -200,14 +225,14 @@ module ActiveRecord
200
225
  autoload :ThroughAssociation
201
226
 
202
227
  module Builder #:nodoc:
203
- autoload :Association, 'active_record/associations/builder/association'
204
- autoload :SingularAssociation, 'active_record/associations/builder/singular_association'
205
- autoload :CollectionAssociation, 'active_record/associations/builder/collection_association'
228
+ autoload :Association, "active_record/associations/builder/association"
229
+ autoload :SingularAssociation, "active_record/associations/builder/singular_association"
230
+ autoload :CollectionAssociation, "active_record/associations/builder/collection_association"
206
231
 
207
- autoload :BelongsTo, 'active_record/associations/builder/belongs_to'
208
- autoload :HasOne, 'active_record/associations/builder/has_one'
209
- autoload :HasMany, 'active_record/associations/builder/has_many'
210
- autoload :HasAndBelongsToMany, 'active_record/associations/builder/has_and_belongs_to_many'
232
+ autoload :BelongsTo, "active_record/associations/builder/belongs_to"
233
+ autoload :HasOne, "active_record/associations/builder/has_one"
234
+ autoload :HasMany, "active_record/associations/builder/has_many"
235
+ autoload :HasAndBelongsToMany, "active_record/associations/builder/has_and_belongs_to_many"
211
236
  end
212
237
 
213
238
  eager_autoload do
@@ -260,16 +285,16 @@ module ActiveRecord
260
285
 
261
286
  private
262
287
  # Clears out the association cache.
263
- def clear_association_cache # :nodoc:
288
+ def clear_association_cache
264
289
  @association_cache.clear if persisted?
265
290
  end
266
291
 
267
- def init_internals # :nodoc:
292
+ def init_internals
268
293
  @association_cache = {}
269
294
  super
270
295
  end
271
296
 
272
- # Returns the specified association instance if it exists, nil otherwise.
297
+ # Returns the specified association instance if it exists, +nil+ otherwise.
273
298
  def association_instance_get(name)
274
299
  @association_cache[name]
275
300
  end
@@ -279,1576 +304,1580 @@ module ActiveRecord
279
304
  @association_cache[name] = association
280
305
  end
281
306
 
282
- # \Associations are a set of macro-like class methods for tying objects together through
283
- # foreign keys. They express relationships like "Project has one Project Manager"
284
- # or "Project belongs to a Portfolio". Each macro adds a number of methods to the
285
- # class which are specialized according to the collection or association symbol and the
286
- # options hash. It works much the same way as Ruby's own <tt>attr*</tt>
287
- # methods.
288
- #
289
- # class Project < ActiveRecord::Base
290
- # belongs_to :portfolio
291
- # has_one :project_manager
292
- # has_many :milestones
293
- # has_and_belongs_to_many :categories
294
- # end
295
- #
296
- # The project class now has the following methods (and more) to ease the traversal and
297
- # manipulation of its relationships:
298
- # * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
299
- # * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
300
- # * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
301
- # <tt>Project#milestones.delete(milestone), Project#milestones.destroy(milestone), Project#milestones.find(milestone_id),</tt>
302
- # <tt>Project#milestones.build, Project#milestones.create</tt>
303
- # * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
304
- # <tt>Project#categories.delete(category1), Project#categories.destroy(category1)</tt>
305
- #
306
- # === A word of warning
307
- #
308
- # Don't create associations that have the same name as instance methods of
309
- # ActiveRecord::Base. Since the association adds a method with that name to
310
- # its model, it will override the inherited method and break things.
311
- # For instance, +attributes+ and +connection+ would be bad choices for association names.
312
- #
313
- # == Auto-generated methods
314
- # See also Instance Public methods below for more details.
315
- #
316
- # === Singular associations (one-to-one)
317
- # | | belongs_to |
318
- # generated methods | belongs_to | :polymorphic | has_one
319
- # ----------------------------------+------------+--------------+---------
320
- # other | X | X | X
321
- # other=(other) | X | X | X
322
- # build_other(attributes={}) | X | | X
323
- # create_other(attributes={}) | X | | X
324
- # create_other!(attributes={}) | X | | X
325
- # reload_other | X | X | X
326
- #
327
- # === Collection associations (one-to-many / many-to-many)
328
- # | | | has_many
329
- # generated methods | habtm | has_many | :through
330
- # ----------------------------------+-------+----------+----------
331
- # others | X | X | X
332
- # others=(other,other,...) | X | X | X
333
- # other_ids | X | X | X
334
- # other_ids=(id,id,...) | X | X | X
335
- # others<< | X | X | X
336
- # others.push | X | X | X
337
- # others.concat | X | X | X
338
- # others.build(attributes={}) | X | X | X
339
- # others.create(attributes={}) | X | X | X
340
- # others.create!(attributes={}) | X | X | X
341
- # others.size | X | X | X
342
- # others.length | X | X | X
343
- # others.count | X | X | X
344
- # others.sum(*args) | X | X | X
345
- # others.empty? | X | X | X
346
- # others.clear | X | X | X
347
- # others.delete(other,other,...) | X | X | X
348
- # others.delete_all | X | X | X
349
- # others.destroy(other,other,...) | X | X | X
350
- # others.destroy_all | X | X | X
351
- # others.find(*args) | X | X | X
352
- # others.exists? | X | X | X
353
- # others.distinct | X | X | X
354
- # others.reset | X | X | X
355
- # others.reload | X | X | X
356
- #
357
- # === Overriding generated methods
358
- #
359
- # Association methods are generated in a module that is included into the model class,
360
- # which allows you to easily override with your own methods and call the original
361
- # generated method with +super+. For example:
362
- #
363
- # class Car < ActiveRecord::Base
364
- # belongs_to :owner
365
- # belongs_to :old_owner
366
- # def owner=(new_owner)
367
- # self.old_owner = self.owner
368
- # super
369
- # end
370
- # end
371
- #
372
- # If your model class is <tt>Project</tt>, the module is
373
- # named <tt>Project::GeneratedAssociationMethods</tt>. The +GeneratedAssociationMethods+ module is
374
- # included in the model class immediately after the (anonymous) generated attributes methods
375
- # module, meaning an association will override the methods for an attribute with the same name.
376
- #
377
- # == Cardinality and associations
378
- #
379
- # Active Record associations can be used to describe one-to-one, one-to-many and many-to-many
380
- # relationships between models. Each model uses an association to describe its role in
381
- # the relation. The #belongs_to association is always used in the model that has
382
- # the foreign key.
383
- #
384
- # === One-to-one
385
- #
386
- # Use #has_one in the base, and #belongs_to in the associated model.
387
- #
388
- # class Employee < ActiveRecord::Base
389
- # has_one :office
390
- # end
391
- # class Office < ActiveRecord::Base
392
- # belongs_to :employee # foreign key - employee_id
393
- # end
394
- #
395
- # === One-to-many
396
- #
397
- # Use #has_many in the base, and #belongs_to in the associated model.
398
- #
399
- # class Manager < ActiveRecord::Base
400
- # has_many :employees
401
- # end
402
- # class Employee < ActiveRecord::Base
403
- # belongs_to :manager # foreign key - manager_id
404
- # end
405
- #
406
- # === Many-to-many
407
- #
408
- # There are two ways to build a many-to-many relationship.
409
- #
410
- # The first way uses a #has_many association with the <tt>:through</tt> option and a join model, so
411
- # there are two stages of associations.
412
- #
413
- # class Assignment < ActiveRecord::Base
414
- # belongs_to :programmer # foreign key - programmer_id
415
- # belongs_to :project # foreign key - project_id
416
- # end
417
- # class Programmer < ActiveRecord::Base
418
- # has_many :assignments
419
- # has_many :projects, through: :assignments
420
- # end
421
- # class Project < ActiveRecord::Base
422
- # has_many :assignments
423
- # has_many :programmers, through: :assignments
424
- # end
425
- #
426
- # For the second way, use #has_and_belongs_to_many in both models. This requires a join table
427
- # that has no corresponding model or primary key.
428
- #
429
- # class Programmer < ActiveRecord::Base
430
- # has_and_belongs_to_many :projects # foreign keys in the join table
431
- # end
432
- # class Project < ActiveRecord::Base
433
- # has_and_belongs_to_many :programmers # foreign keys in the join table
434
- # end
435
- #
436
- # Choosing which way to build a many-to-many relationship is not always simple.
437
- # If you need to work with the relationship model as its own entity,
438
- # use #has_many <tt>:through</tt>. Use #has_and_belongs_to_many when working with legacy schemas or when
439
- # you never work directly with the relationship itself.
440
- #
441
- # == Is it a #belongs_to or #has_one association?
442
- #
443
- # Both express a 1-1 relationship. The difference is mostly where to place the foreign
444
- # key, which goes on the table for the class declaring the #belongs_to relationship.
445
- #
446
- # class User < ActiveRecord::Base
447
- # # I reference an account.
448
- # belongs_to :account
449
- # end
450
- #
451
- # class Account < ActiveRecord::Base
452
- # # One user references me.
453
- # has_one :user
454
- # end
455
- #
456
- # The tables for these classes could look something like:
457
- #
458
- # CREATE TABLE users (
459
- # id int NOT NULL auto_increment,
460
- # account_id int default NULL,
461
- # name varchar default NULL,
462
- # PRIMARY KEY (id)
463
- # )
464
- #
465
- # CREATE TABLE accounts (
466
- # id int NOT NULL auto_increment,
467
- # name varchar default NULL,
468
- # PRIMARY KEY (id)
469
- # )
470
- #
471
- # == Unsaved objects and associations
472
- #
473
- # You can manipulate objects and associations before they are saved to the database, but
474
- # there is some special behavior you should be aware of, mostly involving the saving of
475
- # associated objects.
476
- #
477
- # You can set the <tt>:autosave</tt> option on a #has_one, #belongs_to,
478
- # #has_many, or #has_and_belongs_to_many association. Setting it
479
- # to +true+ will _always_ save the members, whereas setting it to +false+ will
480
- # _never_ save the members. More details about <tt>:autosave</tt> option is available at
481
- # AutosaveAssociation.
482
- #
483
- # === One-to-one associations
484
- #
485
- # * Assigning an object to a #has_one association automatically saves that object and
486
- # the object being replaced (if there is one), in order to update their foreign
487
- # keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
488
- # * If either of these saves fail (due to one of the objects being invalid), an
489
- # ActiveRecord::RecordNotSaved exception is raised and the assignment is
490
- # cancelled.
491
- # * If you wish to assign an object to a #has_one association without saving it,
492
- # use the <tt>#build_association</tt> method (documented below). The object being
493
- # replaced will still be saved to update its foreign key.
494
- # * Assigning an object to a #belongs_to association does not save the object, since
495
- # the foreign key field belongs on the parent. It does not save the parent either.
496
- #
497
- # === Collections
498
- #
499
- # * Adding an object to a collection (#has_many or #has_and_belongs_to_many) automatically
500
- # saves that object, except if the parent object (the owner of the collection) is not yet
501
- # stored in the database.
502
- # * If saving any of the objects being added to a collection (via <tt>push</tt> or similar)
503
- # fails, then <tt>push</tt> returns +false+.
504
- # * If saving fails while replacing the collection (via <tt>association=</tt>), an
505
- # ActiveRecord::RecordNotSaved exception is raised and the assignment is
506
- # cancelled.
507
- # * You can add an object to a collection without automatically saving it by using the
508
- # <tt>collection.build</tt> method (documented below).
509
- # * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically
510
- # saved when the parent is saved.
511
- #
512
- # == Customizing the query
513
- #
514
- # \Associations are built from <tt>Relation</tt> objects, and you can use the Relation syntax
515
- # to customize them. For example, to add a condition:
516
- #
517
- # class Blog < ActiveRecord::Base
518
- # has_many :published_posts, -> { where(published: true) }, class_name: 'Post'
519
- # end
520
- #
521
- # Inside the <tt>-> { ... }</tt> block you can use all of the usual Relation methods.
522
- #
523
- # === Accessing the owner object
524
- #
525
- # Sometimes it is useful to have access to the owner object when building the query. The owner
526
- # is passed as a parameter to the block. For example, the following association would find all
527
- # events that occur on the user's birthday:
528
- #
529
- # class User < ActiveRecord::Base
530
- # has_many :birthday_events, ->(user) { where(starts_on: user.birthday) }, class_name: 'Event'
531
- # end
532
- #
533
- # Note: Joining, eager loading and preloading of these associations is not fully possible.
534
- # These operations happen before instance creation and the scope will be called with a +nil+ argument.
535
- # This can lead to unexpected behavior and is deprecated.
536
- #
537
- # == Association callbacks
538
- #
539
- # Similar to the normal callbacks that hook into the life cycle of an Active Record object,
540
- # you can also define callbacks that get triggered when you add an object to or remove an
541
- # object from an association collection.
542
- #
543
- # class Project
544
- # has_and_belongs_to_many :developers, after_add: :evaluate_velocity
545
- #
546
- # def evaluate_velocity(developer)
547
- # ...
548
- # end
549
- # end
550
- #
551
- # It's possible to stack callbacks by passing them as an array. Example:
552
- #
553
- # class Project
554
- # has_and_belongs_to_many :developers,
555
- # after_add: [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
556
- # end
557
- #
558
- # Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+.
559
- #
560
- # If any of the +before_add+ callbacks throw an exception, the object will not be
561
- # added to the collection.
562
- #
563
- # Similarly, if any of the +before_remove+ callbacks throw an exception, the object
564
- # will not be removed from the collection.
565
- #
566
- # == Association extensions
567
- #
568
- # The proxy objects that control the access to associations can be extended through anonymous
569
- # modules. This is especially beneficial for adding new finders, creators, and other
570
- # factory-type methods that are only used as part of this association.
571
- #
572
- # class Account < ActiveRecord::Base
573
- # has_many :people do
574
- # def find_or_create_by_name(name)
575
- # first_name, last_name = name.split(" ", 2)
576
- # find_or_create_by(first_name: first_name, last_name: last_name)
577
- # end
578
- # end
579
- # end
580
- #
581
- # person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson")
582
- # person.first_name # => "David"
583
- # person.last_name # => "Heinemeier Hansson"
584
- #
585
- # If you need to share the same extensions between many associations, you can use a named
586
- # extension module.
587
- #
588
- # module FindOrCreateByNameExtension
589
- # def find_or_create_by_name(name)
590
- # first_name, last_name = name.split(" ", 2)
591
- # find_or_create_by(first_name: first_name, last_name: last_name)
592
- # end
593
- # end
594
- #
595
- # class Account < ActiveRecord::Base
596
- # has_many :people, -> { extending FindOrCreateByNameExtension }
597
- # end
598
- #
599
- # class Company < ActiveRecord::Base
600
- # has_many :people, -> { extending FindOrCreateByNameExtension }
601
- # end
602
- #
603
- # Some extensions can only be made to work with knowledge of the association's internals.
604
- # Extensions can access relevant state using the following methods (where +items+ is the
605
- # name of the association):
606
- #
607
- # * <tt>record.association(:items).owner</tt> - Returns the object the association is part of.
608
- # * <tt>record.association(:items).reflection</tt> - Returns the reflection object that describes the association.
609
- # * <tt>record.association(:items).target</tt> - Returns the associated object for #belongs_to and #has_one, or
610
- # the collection of associated objects for #has_many and #has_and_belongs_to_many.
611
- #
612
- # However, inside the actual extension code, you will not have access to the <tt>record</tt> as
613
- # above. In this case, you can access <tt>proxy_association</tt>. For example,
614
- # <tt>record.association(:items)</tt> and <tt>record.items.proxy_association</tt> will return
615
- # the same object, allowing you to make calls like <tt>proxy_association.owner</tt> inside
616
- # association extensions.
617
- #
618
- # == Association Join Models
619
- #
620
- # Has Many associations can be configured with the <tt>:through</tt> option to use an
621
- # explicit join model to retrieve the data. This operates similarly to a
622
- # #has_and_belongs_to_many association. The advantage is that you're able to add validations,
623
- # callbacks, and extra attributes on the join model. Consider the following schema:
624
- #
625
- # class Author < ActiveRecord::Base
626
- # has_many :authorships
627
- # has_many :books, through: :authorships
628
- # end
629
- #
630
- # class Authorship < ActiveRecord::Base
631
- # belongs_to :author
632
- # belongs_to :book
633
- # end
634
- #
635
- # @author = Author.first
636
- # @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to
637
- # @author.books # selects all books by using the Authorship join model
638
- #
639
- # You can also go through a #has_many association on the join model:
640
- #
641
- # class Firm < ActiveRecord::Base
642
- # has_many :clients
643
- # has_many :invoices, through: :clients
644
- # end
645
- #
646
- # class Client < ActiveRecord::Base
647
- # belongs_to :firm
648
- # has_many :invoices
649
- # end
650
- #
651
- # class Invoice < ActiveRecord::Base
652
- # belongs_to :client
653
- # end
654
- #
655
- # @firm = Firm.first
656
- # @firm.clients.flat_map { |c| c.invoices } # select all invoices for all clients of the firm
657
- # @firm.invoices # selects all invoices by going through the Client join model
658
- #
659
- # Similarly you can go through a #has_one association on the join model:
660
- #
661
- # class Group < ActiveRecord::Base
662
- # has_many :users
663
- # has_many :avatars, through: :users
664
- # end
665
- #
666
- # class User < ActiveRecord::Base
667
- # belongs_to :group
668
- # has_one :avatar
669
- # end
670
- #
671
- # class Avatar < ActiveRecord::Base
672
- # belongs_to :user
673
- # end
674
- #
675
- # @group = Group.first
676
- # @group.users.collect { |u| u.avatar }.compact # select all avatars for all users in the group
677
- # @group.avatars # selects all avatars by going through the User join model.
678
- #
679
- # An important caveat with going through #has_one or #has_many associations on the
680
- # join model is that these associations are *read-only*. For example, the following
681
- # would not work following the previous example:
682
- #
683
- # @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around
684
- # @group.avatars.delete(@group.avatars.last) # so would this
685
- #
686
- # == Setting Inverses
687
- #
688
- # If you are using a #belongs_to on the join model, it is a good idea to set the
689
- # <tt>:inverse_of</tt> option on the #belongs_to, which will mean that the following example
690
- # works correctly (where <tt>tags</tt> is a #has_many <tt>:through</tt> association):
691
- #
692
- # @post = Post.first
693
- # @tag = @post.tags.build name: "ruby"
694
- # @tag.save
695
- #
696
- # The last line ought to save the through record (a <tt>Tagging</tt>). This will only work if the
697
- # <tt>:inverse_of</tt> is set:
698
- #
699
- # class Tagging < ActiveRecord::Base
700
- # belongs_to :post
701
- # belongs_to :tag, inverse_of: :taggings
702
- # end
703
- #
704
- # If you do not set the <tt>:inverse_of</tt> record, the association will
705
- # do its best to match itself up with the correct inverse. Automatic
706
- # inverse detection only works on #has_many, #has_one, and
707
- # #belongs_to associations.
708
- #
709
- # Extra options on the associations, as defined in the
710
- # <tt>AssociationReflection::INVALID_AUTOMATIC_INVERSE_OPTIONS</tt> constant, will
711
- # also prevent the association's inverse from being found automatically.
712
- #
713
- # The automatic guessing of the inverse association uses a heuristic based
714
- # on the name of the class, so it may not work for all associations,
715
- # especially the ones with non-standard names.
716
- #
717
- # You can turn off the automatic detection of inverse associations by setting
718
- # the <tt>:inverse_of</tt> option to <tt>false</tt> like so:
719
- #
720
- # class Tagging < ActiveRecord::Base
721
- # belongs_to :tag, inverse_of: false
722
- # end
723
- #
724
- # == Nested \Associations
725
- #
726
- # You can actually specify *any* association with the <tt>:through</tt> option, including an
727
- # association which has a <tt>:through</tt> option itself. For example:
728
- #
729
- # class Author < ActiveRecord::Base
730
- # has_many :posts
731
- # has_many :comments, through: :posts
732
- # has_many :commenters, through: :comments
733
- # end
734
- #
735
- # class Post < ActiveRecord::Base
736
- # has_many :comments
737
- # end
738
- #
739
- # class Comment < ActiveRecord::Base
740
- # belongs_to :commenter
741
- # end
742
- #
743
- # @author = Author.first
744
- # @author.commenters # => People who commented on posts written by the author
745
- #
746
- # An equivalent way of setting up this association this would be:
747
- #
748
- # class Author < ActiveRecord::Base
749
- # has_many :posts
750
- # has_many :commenters, through: :posts
751
- # end
752
- #
753
- # class Post < ActiveRecord::Base
754
- # has_many :comments
755
- # has_many :commenters, through: :comments
756
- # end
757
- #
758
- # class Comment < ActiveRecord::Base
759
- # belongs_to :commenter
760
- # end
761
- #
762
- # When using a nested association, you will not be able to modify the association because there
763
- # is not enough information to know what modification to make. For example, if you tried to
764
- # add a <tt>Commenter</tt> in the example above, there would be no way to tell how to set up the
765
- # intermediate <tt>Post</tt> and <tt>Comment</tt> objects.
766
- #
767
- # == Polymorphic \Associations
768
- #
769
- # Polymorphic associations on models are not restricted on what types of models they
770
- # can be associated with. Rather, they specify an interface that a #has_many association
771
- # must adhere to.
772
- #
773
- # class Asset < ActiveRecord::Base
774
- # belongs_to :attachable, polymorphic: true
775
- # end
776
- #
777
- # class Post < ActiveRecord::Base
778
- # has_many :assets, as: :attachable # The :as option specifies the polymorphic interface to use.
779
- # end
780
- #
781
- # @asset.attachable = @post
782
- #
783
- # This works by using a type column in addition to a foreign key to specify the associated
784
- # record. In the Asset example, you'd need an +attachable_id+ integer column and an
785
- # +attachable_type+ string column.
786
- #
787
- # Using polymorphic associations in combination with single table inheritance (STI) is
788
- # a little tricky. In order for the associations to work as expected, ensure that you
789
- # store the base model for the STI models in the type column of the polymorphic
790
- # association. To continue with the asset example above, suppose there are guest posts
791
- # and member posts that use the posts table for STI. In this case, there must be a +type+
792
- # column in the posts table.
793
- #
794
- # Note: The <tt>attachable_type=</tt> method is being called when assigning an +attachable+.
795
- # The +class_name+ of the +attachable+ is passed as a String.
796
- #
797
- # class Asset < ActiveRecord::Base
798
- # belongs_to :attachable, polymorphic: true
799
- #
800
- # def attachable_type=(class_name)
801
- # super(class_name.constantize.base_class.to_s)
802
- # end
803
- # end
804
- #
805
- # class Post < ActiveRecord::Base
806
- # # because we store "Post" in attachable_type now dependent: :destroy will work
807
- # has_many :assets, as: :attachable, dependent: :destroy
808
- # end
809
- #
810
- # class GuestPost < Post
811
- # end
812
- #
813
- # class MemberPost < Post
814
- # end
815
- #
816
- # == Caching
817
- #
818
- # All of the methods are built on a simple caching principle that will keep the result
819
- # of the last query around unless specifically instructed not to. The cache is even
820
- # shared across methods to make it even cheaper to use the macro-added methods without
821
- # worrying too much about performance at the first go.
822
- #
823
- # project.milestones # fetches milestones from the database
824
- # project.milestones.size # uses the milestone cache
825
- # project.milestones.empty? # uses the milestone cache
826
- # project.milestones(true).size # fetches milestones from the database
827
- # project.milestones # uses the milestone cache
828
- #
829
- # == Eager loading of associations
830
- #
831
- # Eager loading is a way to find objects of a certain class and a number of named associations.
832
- # It is one of the easiest ways to prevent the dreaded N+1 problem in which fetching 100
833
- # posts that each need to display their author triggers 101 database queries. Through the
834
- # use of eager loading, the number of queries will be reduced from 101 to 2.
835
- #
836
- # class Post < ActiveRecord::Base
837
- # belongs_to :author
838
- # has_many :comments
839
- # end
840
- #
841
- # Consider the following loop using the class above:
842
- #
843
- # Post.all.each do |post|
844
- # puts "Post: " + post.title
845
- # puts "Written by: " + post.author.name
846
- # puts "Last comment on: " + post.comments.first.created_on
847
- # end
848
- #
849
- # To iterate over these one hundred posts, we'll generate 201 database queries. Let's
850
- # first just optimize it for retrieving the author:
851
- #
852
- # Post.includes(:author).each do |post|
853
- #
854
- # This references the name of the #belongs_to association that also used the <tt>:author</tt>
855
- # symbol. After loading the posts, find will collect the +author_id+ from each one and load
856
- # all the referenced authors with one query. Doing so will cut down the number of queries
857
- # from 201 to 102.
858
- #
859
- # We can improve upon the situation further by referencing both associations in the finder with:
860
- #
861
- # Post.includes(:author, :comments).each do |post|
862
- #
863
- # This will load all comments with a single query. This reduces the total number of queries
864
- # to 3. In general, the number of queries will be 1 plus the number of associations
865
- # named (except if some of the associations are polymorphic #belongs_to - see below).
866
- #
867
- # To include a deep hierarchy of associations, use a hash:
868
- #
869
- # Post.includes(:author, { comments: { author: :gravatar } }).each do |post|
870
- #
871
- # The above code will load all the comments and all of their associated
872
- # authors and gravatars. You can mix and match any combination of symbols,
873
- # arrays, and hashes to retrieve the associations you want to load.
874
- #
875
- # All of this power shouldn't fool you into thinking that you can pull out huge amounts
876
- # of data with no performance penalty just because you've reduced the number of queries.
877
- # The database still needs to send all the data to Active Record and it still needs to
878
- # be processed. So it's no catch-all for performance problems, but it's a great way to
879
- # cut down on the number of queries in a situation as the one described above.
880
- #
881
- # Since only one table is loaded at a time, conditions or orders cannot reference tables
882
- # other than the main one. If this is the case, Active Record falls back to the previously
883
- # used LEFT OUTER JOIN based strategy. For example:
884
- #
885
- # Post.includes([:author, :comments]).where(['comments.approved = ?', true])
886
- #
887
- # This will result in a single SQL query with joins along the lines of:
888
- # <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
889
- # <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions
890
- # like this can have unintended consequences.
891
- # In the above example posts with no approved comments are not returned at all, because
892
- # the conditions apply to the SQL statement as a whole and not just to the association.
893
- #
894
- # You must disambiguate column references for this fallback to happen, for example
895
- # <tt>order: "author.name DESC"</tt> will work but <tt>order: "name DESC"</tt> will not.
896
- #
897
- # If you want to load all posts (including posts with no approved comments) then write
898
- # your own LEFT OUTER JOIN query using ON
899
- #
900
- # Post.joins("LEFT OUTER JOIN comments ON comments.post_id = posts.id AND comments.approved = '1'")
901
- #
902
- # In this case it is usually more natural to include an association which has conditions defined on it:
903
- #
904
- # class Post < ActiveRecord::Base
905
- # has_many :approved_comments, -> { where(approved: true) }, class_name: 'Comment'
906
- # end
907
- #
908
- # Post.includes(:approved_comments)
909
- #
910
- # This will load posts and eager load the +approved_comments+ association, which contains
911
- # only those comments that have been approved.
912
- #
913
- # If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored,
914
- # returning all the associated objects:
915
- #
916
- # class Picture < ActiveRecord::Base
917
- # has_many :most_recent_comments, -> { order('id DESC').limit(10) }, class_name: 'Comment'
918
- # end
919
- #
920
- # Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments.
921
- #
922
- # Eager loading is supported with polymorphic associations.
923
- #
924
- # class Address < ActiveRecord::Base
925
- # belongs_to :addressable, polymorphic: true
926
- # end
927
- #
928
- # A call that tries to eager load the addressable model
929
- #
930
- # Address.includes(:addressable)
931
- #
932
- # This will execute one query to load the addresses and load the addressables with one
933
- # query per addressable type.
934
- # For example if all the addressables are either of class Person or Company then a total
935
- # of 3 queries will be executed. The list of addressable types to load is determined on
936
- # the back of the addresses loaded. This is not supported if Active Record has to fallback
937
- # to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError.
938
- # The reason is that the parent model's type is a column value so its corresponding table
939
- # name cannot be put in the +FROM+/+JOIN+ clauses of that query.
940
- #
941
- # == Table Aliasing
942
- #
943
- # Active Record uses table aliasing in the case that a table is referenced multiple times
944
- # in a join. If a table is referenced only once, the standard table name is used. The
945
- # second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>.
946
- # Indexes are appended for any more successive uses of the table name.
947
- #
948
- # Post.joins(:comments)
949
- # # => SELECT ... FROM posts INNER JOIN comments ON ...
950
- # Post.joins(:special_comments) # STI
951
- # # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment'
952
- # Post.joins(:comments, :special_comments) # special_comments is the reflection name, posts is the parent table name
953
- # # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts
954
- #
955
- # Acts as tree example:
956
- #
957
- # TreeMixin.joins(:children)
958
- # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
959
- # TreeMixin.joins(children: :parent)
960
- # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
961
- # INNER JOIN parents_mixins ...
962
- # TreeMixin.joins(children: {parent: :children})
963
- # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
964
- # INNER JOIN parents_mixins ...
965
- # INNER JOIN mixins childrens_mixins_2
966
- #
967
- # Has and Belongs to Many join tables use the same idea, but add a <tt>_join</tt> suffix:
968
- #
969
- # Post.joins(:categories)
970
- # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
971
- # Post.joins(categories: :posts)
972
- # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
973
- # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
974
- # Post.joins(categories: {posts: :categories})
975
- # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
976
- # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
977
- # INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
978
- #
979
- # If you wish to specify your own custom joins using ActiveRecord::QueryMethods#joins method, those table
980
- # names will take precedence over the eager associations:
981
- #
982
- # Post.joins(:comments).joins("inner join comments ...")
983
- # # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...
984
- # Post.joins(:comments, :special_comments).joins("inner join comments ...")
985
- # # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ...
986
- # INNER JOIN comments special_comments_posts ...
987
- # INNER JOIN comments ...
988
- #
989
- # Table aliases are automatically truncated according to the maximum length of table identifiers
990
- # according to the specific database.
991
- #
992
- # == Modules
993
- #
994
- # By default, associations will look for objects within the current module scope. Consider:
995
- #
996
- # module MyApplication
997
- # module Business
998
- # class Firm < ActiveRecord::Base
999
- # has_many :clients
1000
- # end
1001
- #
1002
- # class Client < ActiveRecord::Base; end
1003
- # end
1004
- # end
1005
- #
1006
- # When <tt>Firm#clients</tt> is called, it will in turn call
1007
- # <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>.
1008
- # If you want to associate with a class in another module scope, this can be done by
1009
- # specifying the complete class name.
1010
- #
1011
- # module MyApplication
1012
- # module Business
1013
- # class Firm < ActiveRecord::Base; end
1014
- # end
1015
- #
1016
- # module Billing
1017
- # class Account < ActiveRecord::Base
1018
- # belongs_to :firm, class_name: "MyApplication::Business::Firm"
1019
- # end
1020
- # end
1021
- # end
1022
- #
1023
- # == Bi-directional associations
1024
- #
1025
- # When you specify an association there is usually an association on the associated model
1026
- # that specifies the same relationship in reverse. For example, with the following models:
1027
- #
1028
- # class Dungeon < ActiveRecord::Base
1029
- # has_many :traps
1030
- # has_one :evil_wizard
1031
- # end
1032
- #
1033
- # class Trap < ActiveRecord::Base
1034
- # belongs_to :dungeon
1035
- # end
1036
- #
1037
- # class EvilWizard < ActiveRecord::Base
1038
- # belongs_to :dungeon
1039
- # end
1040
- #
1041
- # The +traps+ association on +Dungeon+ and the +dungeon+ association on +Trap+ are
1042
- # the inverse of each other and the inverse of the +dungeon+ association on +EvilWizard+
1043
- # is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
1044
- # Active Record can guess the inverse of the association based on the name
1045
- # of the class. The result is the following:
1046
- #
1047
- # d = Dungeon.first
1048
- # t = d.traps.first
1049
- # d.object_id == t.dungeon.object_id # => true
1050
- #
1051
- # The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to
1052
- # the same in-memory instance since the association matches the name of the class.
1053
- # The result would be the same if we added +:inverse_of+ to our model definitions:
1054
- #
1055
- # class Dungeon < ActiveRecord::Base
1056
- # has_many :traps, inverse_of: :dungeon
1057
- # has_one :evil_wizard, inverse_of: :dungeon
1058
- # end
1059
- #
1060
- # class Trap < ActiveRecord::Base
1061
- # belongs_to :dungeon, inverse_of: :traps
1062
- # end
1063
- #
1064
- # class EvilWizard < ActiveRecord::Base
1065
- # belongs_to :dungeon, inverse_of: :evil_wizard
1066
- # end
1067
- #
1068
- # There are limitations to <tt>:inverse_of</tt> support:
1069
- #
1070
- # * does not work with <tt>:through</tt> associations.
1071
- # * does not work with <tt>:polymorphic</tt> associations.
1072
- # * for #belongs_to associations #has_many inverse associations are ignored.
1073
- #
1074
- # For more information, see the documentation for the +:inverse_of+ option.
1075
- #
1076
- # == Deleting from associations
1077
- #
1078
- # === Dependent associations
1079
- #
1080
- # #has_many, #has_one and #belongs_to associations support the <tt>:dependent</tt> option.
1081
- # This allows you to specify that associated records should be deleted when the owner is
1082
- # deleted.
1083
- #
1084
- # For example:
1085
- #
1086
- # class Author
1087
- # has_many :posts, dependent: :destroy
1088
- # end
1089
- # Author.find(1).destroy # => Will destroy all of the author's posts, too
1090
- #
1091
- # The <tt>:dependent</tt> option can have different values which specify how the deletion
1092
- # is done. For more information, see the documentation for this option on the different
1093
- # specific association types. When no option is given, the behavior is to do nothing
1094
- # with the associated records when destroying a record.
1095
- #
1096
- # Note that <tt>:dependent</tt> is implemented using Rails' callback
1097
- # system, which works by processing callbacks in order. Therefore, other
1098
- # callbacks declared either before or after the <tt>:dependent</tt> option
1099
- # can affect what it does.
1100
- #
1101
- # Note that <tt>:dependent</tt> option is ignored for #has_one <tt>:through</tt> associations.
1102
- #
1103
- # === Delete or destroy?
1104
- #
1105
- # #has_many and #has_and_belongs_to_many associations have the methods <tt>destroy</tt>,
1106
- # <tt>delete</tt>, <tt>destroy_all</tt> and <tt>delete_all</tt>.
1107
- #
1108
- # For #has_and_belongs_to_many, <tt>delete</tt> and <tt>destroy</tt> are the same: they
1109
- # cause the records in the join table to be removed.
1110
- #
1111
- # For #has_many, <tt>destroy</tt> and <tt>destroy_all</tt> will always call the <tt>destroy</tt> method of the
1112
- # record(s) being removed so that callbacks are run. However <tt>delete</tt> and <tt>delete_all</tt> will either
1113
- # do the deletion according to the strategy specified by the <tt>:dependent</tt> option, or
1114
- # if no <tt>:dependent</tt> option is given, then it will follow the default strategy.
1115
- # The default strategy is to do nothing (leave the foreign keys with the parent ids set), except for
1116
- # #has_many <tt>:through</tt>, where the default strategy is <tt>delete_all</tt> (delete
1117
- # the join records, without running their callbacks).
1118
- #
1119
- # There is also a <tt>clear</tt> method which is the same as <tt>delete_all</tt>, except that
1120
- # it returns the association rather than the records which have been deleted.
1121
- #
1122
- # === What gets deleted?
1123
- #
1124
- # There is a potential pitfall here: #has_and_belongs_to_many and #has_many <tt>:through</tt>
1125
- # associations have records in join tables, as well as the associated records. So when we
1126
- # call one of these deletion methods, what exactly should be deleted?
1127
- #
1128
- # The answer is that it is assumed that deletion on an association is about removing the
1129
- # <i>link</i> between the owner and the associated object(s), rather than necessarily the
1130
- # associated objects themselves. So with #has_and_belongs_to_many and #has_many
1131
- # <tt>:through</tt>, the join records will be deleted, but the associated records won't.
1132
- #
1133
- # This makes sense if you think about it: if you were to call <tt>post.tags.delete(Tag.find_by(name: 'food'))</tt>
1134
- # you would want the 'food' tag to be unlinked from the post, rather than for the tag itself
1135
- # to be removed from the database.
1136
- #
1137
- # However, there are examples where this strategy doesn't make sense. For example, suppose
1138
- # a person has many projects, and each project has many tasks. If we deleted one of a person's
1139
- # tasks, we would probably not want the project to be deleted. In this scenario, the delete method
1140
- # won't actually work: it can only be used if the association on the join model is a
1141
- # #belongs_to. In other situations you are expected to perform operations directly on
1142
- # either the associated records or the <tt>:through</tt> association.
1143
- #
1144
- # With a regular #has_many there is no distinction between the "associated records"
1145
- # and the "link", so there is only one choice for what gets deleted.
1146
- #
1147
- # With #has_and_belongs_to_many and #has_many <tt>:through</tt>, if you want to delete the
1148
- # associated records themselves, you can always do something along the lines of
1149
- # <tt>person.tasks.each(&:destroy)</tt>.
1150
- #
1151
- # == Type safety with ActiveRecord::AssociationTypeMismatch
1152
- #
1153
- # If you attempt to assign an object to an association that doesn't match the inferred
1154
- # or specified <tt>:class_name</tt>, you'll get an ActiveRecord::AssociationTypeMismatch.
1155
- #
1156
- # == Options
1157
- #
1158
- # All of the association macros can be specialized through options. This makes cases
1159
- # more complex than the simple and guessable ones possible.
1160
- module ClassMethods
1161
- # Specifies a one-to-many association. The following methods for retrieval and query of
1162
- # collections of associated objects will be added:
1163
- #
1164
- # +collection+ is a placeholder for the symbol passed as the +name+ argument, so
1165
- # <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.
1166
- #
1167
- # [collection]
1168
- # Returns a Relation of all the associated objects.
1169
- # An empty Relation is returned if none are found.
1170
- # [collection<<(object, ...)]
1171
- # Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
1172
- # Note that this operation instantly fires update SQL without waiting for the save or update call on the
1173
- # parent object, unless the parent object is a new record.
1174
- # This will also run validations and callbacks of associated object(s).
1175
- # [collection.delete(object, ...)]
1176
- # Removes one or more objects from the collection by setting their foreign keys to +NULL+.
1177
- # Objects will be in addition destroyed if they're associated with <tt>dependent: :destroy</tt>,
1178
- # and deleted if they're associated with <tt>dependent: :delete_all</tt>.
1179
- #
1180
- # If the <tt>:through</tt> option is used, then the join records are deleted (rather than
1181
- # nullified) by default, but you can specify <tt>dependent: :destroy</tt> or
1182
- # <tt>dependent: :nullify</tt> to override this.
1183
- # [collection.destroy(object, ...)]
1184
- # Removes one or more objects from the collection by running <tt>destroy</tt> on
1185
- # each record, regardless of any dependent option, ensuring callbacks are run.
1186
- #
1187
- # If the <tt>:through</tt> option is used, then the join records are destroyed
1188
- # instead, not the objects themselves.
1189
- # [collection=objects]
1190
- # Replaces the collections content by deleting and adding objects as appropriate. If the <tt>:through</tt>
1191
- # option is true callbacks in the join models are triggered except destroy callbacks, since deletion is
1192
- # direct by default. You can specify <tt>dependent: :destroy</tt> or
1193
- # <tt>dependent: :nullify</tt> to override this.
1194
- # [collection_singular_ids]
1195
- # Returns an array of the associated objects' ids
1196
- # [collection_singular_ids=ids]
1197
- # Replace the collection with the objects identified by the primary keys in +ids+. This
1198
- # method loads the models and calls <tt>collection=</tt>. See above.
1199
- # [collection.clear]
1200
- # Removes every object from the collection. This destroys the associated objects if they
1201
- # are associated with <tt>dependent: :destroy</tt>, deletes them directly from the
1202
- # database if <tt>dependent: :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
1203
- # If the <tt>:through</tt> option is true no destroy callbacks are invoked on the join models.
1204
- # Join models are directly deleted.
1205
- # [collection.empty?]
1206
- # Returns +true+ if there are no associated objects.
1207
- # [collection.size]
1208
- # Returns the number of associated objects.
1209
- # [collection.find(...)]
1210
- # Finds an associated object according to the same rules as ActiveRecord::FinderMethods#find.
1211
- # [collection.exists?(...)]
1212
- # Checks whether an associated object with the given conditions exists.
1213
- # Uses the same rules as ActiveRecord::FinderMethods#exists?.
1214
- # [collection.build(attributes = {}, ...)]
1215
- # Returns one or more new objects of the collection type that have been instantiated
1216
- # with +attributes+ and linked to this object through a foreign key, but have not yet
1217
- # been saved.
1218
- # [collection.create(attributes = {})]
1219
- # Returns a new object of the collection type that has been instantiated
1220
- # with +attributes+, linked to this object through a foreign key, and that has already
1221
- # been saved (if it passed the validation). *Note*: This only works if the base model
1222
- # already exists in the DB, not if it is a new (unsaved) record!
1223
- # [collection.create!(attributes = {})]
1224
- # Does the same as <tt>collection.create</tt>, but raises ActiveRecord::RecordInvalid
1225
- # if the record is invalid.
1226
- # [collection.reload]
1227
- # Returns a Relation of all of the associated objects, forcing a database read.
1228
- # An empty Relation is returned if none are found.
1229
- #
1230
- # === Example
1231
- #
1232
- # A <tt>Firm</tt> class declares <tt>has_many :clients</tt>, which will add:
1233
- # * <tt>Firm#clients</tt> (similar to <tt>Client.where(firm_id: id)</tt>)
1234
- # * <tt>Firm#clients<<</tt>
1235
- # * <tt>Firm#clients.delete</tt>
1236
- # * <tt>Firm#clients.destroy</tt>
1237
- # * <tt>Firm#clients=</tt>
1238
- # * <tt>Firm#client_ids</tt>
1239
- # * <tt>Firm#client_ids=</tt>
1240
- # * <tt>Firm#clients.clear</tt>
1241
- # * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
1242
- # * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
1243
- # * <tt>Firm#clients.find</tt> (similar to <tt>Client.where(firm_id: id).find(id)</tt>)
1244
- # * <tt>Firm#clients.exists?(name: 'ACME')</tt> (similar to <tt>Client.exists?(name: 'ACME', firm_id: firm.id)</tt>)
1245
- # * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
1246
- # * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
1247
- # * <tt>Firm#clients.create!</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save!</tt>)
1248
- # * <tt>Firm#clients.reload</tt>
1249
- # The declaration can also include an +options+ hash to specialize the behavior of the association.
1250
- #
1251
- # === Scopes
1252
- #
1253
- # You can pass a second argument +scope+ as a callable (i.e. proc or
1254
- # lambda) to retrieve a specific set of records or customize the generated
1255
- # query when you access the associated collection.
1256
- #
1257
- # Scope examples:
1258
- # has_many :comments, -> { where(author_id: 1) }
1259
- # has_many :employees, -> { joins(:address) }
1260
- # has_many :posts, ->(post) { where("max_post_length > ?", post.length) }
1261
- #
1262
- # === Extensions
1263
- #
1264
- # The +extension+ argument allows you to pass a block into a has_many
1265
- # association. This is useful for adding new finders, creators and other
1266
- # factory-type methods to be used as part of the association.
1267
- #
1268
- # Extension examples:
1269
- # has_many :employees do
1270
- # def find_or_create_by_name(name)
1271
- # first_name, last_name = name.split(" ", 2)
1272
- # find_or_create_by(first_name: first_name, last_name: last_name)
307
+ # \Associations are a set of macro-like class methods for tying objects together through
308
+ # foreign keys. They express relationships like "Project has one Project Manager"
309
+ # or "Project belongs to a Portfolio". Each macro adds a number of methods to the
310
+ # class which are specialized according to the collection or association symbol and the
311
+ # options hash. It works much the same way as Ruby's own <tt>attr*</tt>
312
+ # methods.
313
+ #
314
+ # class Project < ActiveRecord::Base
315
+ # belongs_to :portfolio
316
+ # has_one :project_manager
317
+ # has_many :milestones
318
+ # has_and_belongs_to_many :categories
319
+ # end
320
+ #
321
+ # The project class now has the following methods (and more) to ease the traversal and
322
+ # manipulation of its relationships:
323
+ # * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
324
+ # * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
325
+ # * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
326
+ # <tt>Project#milestones.delete(milestone), Project#milestones.destroy(milestone), Project#milestones.find(milestone_id),</tt>
327
+ # <tt>Project#milestones.build, Project#milestones.create</tt>
328
+ # * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
329
+ # <tt>Project#categories.delete(category1), Project#categories.destroy(category1)</tt>
330
+ #
331
+ # === A word of warning
332
+ #
333
+ # Don't create associations that have the same name as {instance methods}[rdoc-ref:ActiveRecord::Core] of
334
+ # <tt>ActiveRecord::Base</tt>. Since the association adds a method with that name to
335
+ # its model, using an association with the same name as one provided by <tt>ActiveRecord::Base</tt> will override the method inherited through <tt>ActiveRecord::Base</tt> and will break things.
336
+ # For instance, +attributes+ and +connection+ would be bad choices for association names, because those names already exist in the list of <tt>ActiveRecord::Base</tt> instance methods.
337
+ #
338
+ # == Auto-generated methods
339
+ # See also Instance Public methods below for more details.
340
+ #
341
+ # === Singular associations (one-to-one)
342
+ # | | belongs_to |
343
+ # generated methods | belongs_to | :polymorphic | has_one
344
+ # ----------------------------------+------------+--------------+---------
345
+ # other | X | X | X
346
+ # other=(other) | X | X | X
347
+ # build_other(attributes={}) | X | | X
348
+ # create_other(attributes={}) | X | | X
349
+ # create_other!(attributes={}) | X | | X
350
+ # reload_other | X | X | X
351
+ #
352
+ # === Collection associations (one-to-many / many-to-many)
353
+ # | | | has_many
354
+ # generated methods | habtm | has_many | :through
355
+ # ----------------------------------+-------+----------+----------
356
+ # others | X | X | X
357
+ # others=(other,other,...) | X | X | X
358
+ # other_ids | X | X | X
359
+ # other_ids=(id,id,...) | X | X | X
360
+ # others<< | X | X | X
361
+ # others.push | X | X | X
362
+ # others.concat | X | X | X
363
+ # others.build(attributes={}) | X | X | X
364
+ # others.create(attributes={}) | X | X | X
365
+ # others.create!(attributes={}) | X | X | X
366
+ # others.size | X | X | X
367
+ # others.length | X | X | X
368
+ # others.count | X | X | X
369
+ # others.sum(*args) | X | X | X
370
+ # others.empty? | X | X | X
371
+ # others.clear | X | X | X
372
+ # others.delete(other,other,...) | X | X | X
373
+ # others.delete_all | X | X | X
374
+ # others.destroy(other,other,...) | X | X | X
375
+ # others.destroy_all | X | X | X
376
+ # others.find(*args) | X | X | X
377
+ # others.exists? | X | X | X
378
+ # others.distinct | X | X | X
379
+ # others.reset | X | X | X
380
+ # others.reload | X | X | X
381
+ #
382
+ # === Overriding generated methods
383
+ #
384
+ # Association methods are generated in a module included into the model
385
+ # class, making overrides easy. The original generated method can thus be
386
+ # called with +super+:
387
+ #
388
+ # class Car < ActiveRecord::Base
389
+ # belongs_to :owner
390
+ # belongs_to :old_owner
391
+ #
392
+ # def owner=(new_owner)
393
+ # self.old_owner = self.owner
394
+ # super
1273
395
  # end
1274
396
  # end
1275
397
  #
1276
- # === Options
1277
- # [:class_name]
1278
- # Specify the class name of the association. Use it only if that name can't be inferred
1279
- # from the association name. So <tt>has_many :products</tt> will by default be linked
1280
- # to the +Product+ class, but if the real class name is +SpecialProduct+, you'll have to
1281
- # specify it with this option.
1282
- # [:foreign_key]
1283
- # Specify the foreign key used for the association. By default this is guessed to be the name
1284
- # of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_many
1285
- # association will use "person_id" as the default <tt>:foreign_key</tt>.
1286
- # [:foreign_type]
1287
- # Specify the column used to store the associated object's type, if this is a polymorphic
1288
- # association. By default this is guessed to be the name of the polymorphic association
1289
- # specified on "as" option with a "_type" suffix. So a class that defines a
1290
- # <tt>has_many :tags, as: :taggable</tt> association will use "taggable_type" as the
1291
- # default <tt>:foreign_type</tt>.
1292
- # [:primary_key]
1293
- # Specify the name of the column to use as the primary key for the association. By default this is +id+.
1294
- # [:dependent]
1295
- # Controls what happens to the associated objects when
1296
- # their owner is destroyed. Note that these are implemented as
1297
- # callbacks, and Rails executes callbacks in order. Therefore, other
1298
- # similar callbacks may affect the <tt>:dependent</tt> behavior, and the
1299
- # <tt>:dependent</tt> behavior may affect other callbacks.
1300
- #
1301
- # * <tt>:destroy</tt> causes all the associated objects to also be destroyed.
1302
- # * <tt>:delete_all</tt> causes all the associated objects to be deleted directly from the database (so callbacks will not be executed).
1303
- # * <tt>:nullify</tt> causes the foreign keys to be set to +NULL+. Callbacks are not executed.
1304
- # * <tt>:restrict_with_exception</tt> causes an exception to be raised if there are any associated records.
1305
- # * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there are any associated objects.
1306
- #
1307
- # If using with the <tt>:through</tt> option, the association on the join model must be
1308
- # a #belongs_to, and the records which get deleted are the join records, rather than
1309
- # the associated records.
1310
- # [:counter_cache]
1311
- # This option can be used to configure a custom named <tt>:counter_cache.</tt> You only need this option,
1312
- # when you customized the name of your <tt>:counter_cache</tt> on the #belongs_to association.
1313
- # [:as]
1314
- # Specifies a polymorphic interface (See #belongs_to).
1315
- # [:through]
1316
- # Specifies an association through which to perform the query. This can be any other type
1317
- # of association, including other <tt>:through</tt> associations. Options for <tt>:class_name</tt>,
1318
- # <tt>:primary_key</tt> and <tt>:foreign_key</tt> are ignored, as the association uses the
1319
- # source reflection.
1320
- #
1321
- # If the association on the join model is a #belongs_to, the collection can be modified
1322
- # and the records on the <tt>:through</tt> model will be automatically created and removed
1323
- # as appropriate. Otherwise, the collection is read-only, so you should manipulate the
1324
- # <tt>:through</tt> association directly.
1325
- #
1326
- # If you are going to modify the association (rather than just read from it), then it is
1327
- # a good idea to set the <tt>:inverse_of</tt> option on the source association on the
1328
- # join model. This allows associated records to be built which will automatically create
1329
- # the appropriate join model records when they are saved. (See the 'Association Join Models'
1330
- # section above.)
1331
- # [:source]
1332
- # Specifies the source association name used by #has_many <tt>:through</tt> queries.
1333
- # Only use it if the name cannot be inferred from the association.
1334
- # <tt>has_many :subscribers, through: :subscriptions</tt> will look for either <tt>:subscribers</tt> or
1335
- # <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
1336
- # [:source_type]
1337
- # Specifies type of the source association used by #has_many <tt>:through</tt> queries where the source
1338
- # association is a polymorphic #belongs_to.
1339
- # [:validate]
1340
- # When set to +true+, validates new objects added to association when saving the parent object. +true+ by default.
1341
- # If you want to ensure associated objects are revalidated on every update, use +validates_associated+.
1342
- # [:autosave]
1343
- # If true, always save the associated objects or destroy them if marked for destruction,
1344
- # when saving the parent object. If false, never save or destroy the associated objects.
1345
- # By default, only save associated objects that are new records. This option is implemented as a
1346
- # +before_save+ callback. Because callbacks are run in the order they are defined, associated objects
1347
- # may need to be explicitly saved in any user-defined +before_save+ callbacks.
1348
- #
1349
- # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets
1350
- # <tt>:autosave</tt> to <tt>true</tt>.
1351
- # [:inverse_of]
1352
- # Specifies the name of the #belongs_to association on the associated object
1353
- # that is the inverse of this #has_many association. Does not work in combination
1354
- # with <tt>:through</tt> or <tt>:as</tt> options.
1355
- # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
1356
- # [:extend]
1357
- # Specifies a module or array of modules that will be extended into the association object returned.
1358
- # Useful for defining methods on associations, especially when they should be shared between multiple
1359
- # association objects.
1360
- #
1361
- # Option examples:
1362
- # has_many :comments, -> { order("posted_on") }
1363
- # has_many :comments, -> { includes(:author) }
1364
- # has_many :people, -> { where(deleted: false).order("name") }, class_name: "Person"
1365
- # has_many :tracks, -> { order("position") }, dependent: :destroy
1366
- # has_many :comments, dependent: :nullify
1367
- # has_many :tags, as: :taggable
1368
- # has_many :reports, -> { readonly }
1369
- # has_many :subscribers, through: :subscriptions, source: :user
1370
- def has_many(name, scope = nil, options = {}, &extension)
1371
- reflection = Builder::HasMany.build(self, name, scope, options, &extension)
1372
- Reflection.add_reflection self, name, reflection
1373
- end
1374
-
1375
- # Specifies a one-to-one association with another class. This method should only be used
1376
- # if the other class contains the foreign key. If the current class contains the foreign key,
1377
- # then you should use #belongs_to instead. See also ActiveRecord::Associations::ClassMethods's overview
1378
- # on when to use #has_one and when to use #belongs_to.
1379
- #
1380
- # The following methods for retrieval and query of a single associated object will be added:
1381
- #
1382
- # +association+ is a placeholder for the symbol passed as the +name+ argument, so
1383
- # <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.
1384
- #
1385
- # [association]
1386
- # Returns the associated object. +nil+ is returned if none is found.
1387
- # [association=(associate)]
1388
- # Assigns the associate object, extracts the primary key, sets it as the foreign key,
1389
- # and saves the associate object. To avoid database inconsistencies, permanently deletes an existing
1390
- # associated object when assigning a new one, even if the new one isn't saved to database.
1391
- # [build_association(attributes = {})]
1392
- # Returns a new object of the associated type that has been instantiated
1393
- # with +attributes+ and linked to this object through a foreign key, but has not
1394
- # yet been saved.
1395
- # [create_association(attributes = {})]
1396
- # Returns a new object of the associated type that has been instantiated
1397
- # with +attributes+, linked to this object through a foreign key, and that
1398
- # has already been saved (if it passed the validation).
1399
- # [create_association!(attributes = {})]
1400
- # Does the same as <tt>create_association</tt>, but raises ActiveRecord::RecordInvalid
1401
- # if the record is invalid.
1402
- # [reload_association]
1403
- # Returns the associated object, forcing a database read.
1404
- #
1405
- # === Example
1406
- #
1407
- # An Account class declares <tt>has_one :beneficiary</tt>, which will add:
1408
- # * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.where(account_id: id).first</tt>)
1409
- # * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
1410
- # * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
1411
- # * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
1412
- # * <tt>Account#create_beneficiary!</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save!; b</tt>)
1413
- # * <tt>Account#reload_beneficiary</tt>
1414
- #
1415
- # === Scopes
1416
- #
1417
- # You can pass a second argument +scope+ as a callable (i.e. proc or
1418
- # lambda) to retrieve a specific record or customize the generated query
1419
- # when you access the associated object.
1420
- #
1421
- # Scope examples:
1422
- # has_one :author, -> { where(comment_id: 1) }
1423
- # has_one :employer, -> { joins(:company) }
1424
- # has_one :dob, ->(dob) { where("Date.new(2000, 01, 01) > ?", dob) }
1425
- #
1426
- # === Options
1427
- #
1428
- # The declaration can also include an +options+ hash to specialize the behavior of the association.
1429
- #
1430
- # Options are:
1431
- # [:class_name]
1432
- # Specify the class name of the association. Use it only if that name can't be inferred
1433
- # from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
1434
- # if the real class name is Person, you'll have to specify it with this option.
1435
- # [:dependent]
1436
- # Controls what happens to the associated object when
1437
- # its owner is destroyed:
1438
- #
1439
- # * <tt>:destroy</tt> causes the associated object to also be destroyed
1440
- # * <tt>:delete</tt> causes the associated object to be deleted directly from the database (so callbacks will not execute)
1441
- # * <tt>:nullify</tt> causes the foreign key to be set to +NULL+. Callbacks are not executed.
1442
- # * <tt>:restrict_with_exception</tt> causes an exception to be raised if there is an associated record
1443
- # * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there is an associated object
1444
- #
1445
- # Note that <tt>:dependent</tt> option is ignored when using <tt>:through</tt> option.
1446
- # [:foreign_key]
1447
- # Specify the foreign key used for the association. By default this is guessed to be the name
1448
- # of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_one association
1449
- # will use "person_id" as the default <tt>:foreign_key</tt>.
1450
- # [:foreign_type]
1451
- # Specify the column used to store the associated object's type, if this is a polymorphic
1452
- # association. By default this is guessed to be the name of the polymorphic association
1453
- # specified on "as" option with a "_type" suffix. So a class that defines a
1454
- # <tt>has_one :tag, as: :taggable</tt> association will use "taggable_type" as the
1455
- # default <tt>:foreign_type</tt>.
1456
- # [:primary_key]
1457
- # Specify the method that returns the primary key used for the association. By default this is +id+.
1458
- # [:as]
1459
- # Specifies a polymorphic interface (See #belongs_to).
1460
- # [:through]
1461
- # Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>,
1462
- # <tt>:primary_key</tt>, and <tt>:foreign_key</tt> are ignored, as the association uses the
1463
- # source reflection. You can only use a <tt>:through</tt> query through a #has_one
1464
- # or #belongs_to association on the join model.
1465
- # [:source]
1466
- # Specifies the source association name used by #has_one <tt>:through</tt> queries.
1467
- # Only use it if the name cannot be inferred from the association.
1468
- # <tt>has_one :favorite, through: :favorites</tt> will look for a
1469
- # <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
1470
- # [:source_type]
1471
- # Specifies type of the source association used by #has_one <tt>:through</tt> queries where the source
1472
- # association is a polymorphic #belongs_to.
1473
- # [:validate]
1474
- # When set to +true+, validates new objects added to association when saving the parent object. +false+ by default.
1475
- # If you want to ensure associated objects are revalidated on every update, use +validates_associated+.
1476
- # [:autosave]
1477
- # If true, always save the associated object or destroy it if marked for destruction,
1478
- # when saving the parent object. If false, never save or destroy the associated object.
1479
- # By default, only save the associated object if it's a new record.
1480
- #
1481
- # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets
1482
- # <tt>:autosave</tt> to <tt>true</tt>.
1483
- # [:inverse_of]
1484
- # Specifies the name of the #belongs_to association on the associated object
1485
- # that is the inverse of this #has_one association. Does not work in combination
1486
- # with <tt>:through</tt> or <tt>:as</tt> options.
1487
- # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
1488
- # [:required]
1489
- # When set to +true+, the association will also have its presence validated.
1490
- # This will validate the association itself, not the id. You can use
1491
- # +:inverse_of+ to avoid an extra query during validation.
1492
- #
1493
- # Option examples:
1494
- # has_one :credit_card, dependent: :destroy # destroys the associated credit card
1495
- # has_one :credit_card, dependent: :nullify # updates the associated records foreign
1496
- # # key value to NULL rather than destroying it
1497
- # has_one :last_comment, -> { order('posted_on') }, class_name: "Comment"
1498
- # has_one :project_manager, -> { where(role: 'project_manager') }, class_name: "Person"
1499
- # has_one :attachment, as: :attachable
1500
- # has_one :boss, -> { readonly }
1501
- # has_one :club, through: :membership
1502
- # has_one :primary_address, -> { where(primary: true) }, through: :addressables, source: :addressable
1503
- # has_one :credit_card, required: true
1504
- def has_one(name, scope = nil, options = {})
1505
- reflection = Builder::HasOne.build(self, name, scope, options)
1506
- Reflection.add_reflection self, name, reflection
1507
- end
1508
-
1509
- # Specifies a one-to-one association with another class. This method should only be used
1510
- # if this class contains the foreign key. If the other class contains the foreign key,
1511
- # then you should use #has_one instead. See also ActiveRecord::Associations::ClassMethods's overview
1512
- # on when to use #has_one and when to use #belongs_to.
1513
- #
1514
- # Methods will be added for retrieval and query for a single associated object, for which
1515
- # this object holds an id:
1516
- #
1517
- # +association+ is a placeholder for the symbol passed as the +name+ argument, so
1518
- # <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.
1519
- #
1520
- # [association]
1521
- # Returns the associated object. +nil+ is returned if none is found.
1522
- # [association=(associate)]
1523
- # Assigns the associate object, extracts the primary key, and sets it as the foreign key.
1524
- # [build_association(attributes = {})]
1525
- # Returns a new object of the associated type that has been instantiated
1526
- # with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
1527
- # [create_association(attributes = {})]
1528
- # Returns a new object of the associated type that has been instantiated
1529
- # with +attributes+, linked to this object through a foreign key, and that
1530
- # has already been saved (if it passed the validation).
1531
- # [create_association!(attributes = {})]
1532
- # Does the same as <tt>create_association</tt>, but raises ActiveRecord::RecordInvalid
1533
- # if the record is invalid.
1534
- # [reload_association]
1535
- # Returns the associated object, forcing a database read.
1536
- #
1537
- # === Example
1538
- #
1539
- # A Post class declares <tt>belongs_to :author</tt>, which will add:
1540
- # * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
1541
- # * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
1542
- # * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
1543
- # * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
1544
- # * <tt>Post#create_author!</tt> (similar to <tt>post.author = Author.new; post.author.save!; post.author</tt>)
1545
- # * <tt>Post#reload_author</tt>
1546
- # The declaration can also include an +options+ hash to specialize the behavior of the association.
1547
- #
1548
- # === Scopes
1549
- #
1550
- # You can pass a second argument +scope+ as a callable (i.e. proc or
1551
- # lambda) to retrieve a specific record or customize the generated query
1552
- # when you access the associated object.
1553
- #
1554
- # Scope examples:
1555
- # belongs_to :firm, -> { where(id: 2) }
1556
- # belongs_to :user, -> { joins(:friends) }
1557
- # belongs_to :level, ->(level) { where("game_level > ?", level.current) }
1558
- #
1559
- # === Options
1560
- #
1561
- # [:class_name]
1562
- # Specify the class name of the association. Use it only if that name can't be inferred
1563
- # from the association name. So <tt>belongs_to :author</tt> will by default be linked to the Author class, but
1564
- # if the real class name is Person, you'll have to specify it with this option.
1565
- # [:foreign_key]
1566
- # Specify the foreign key used for the association. By default this is guessed to be the name
1567
- # of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
1568
- # association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly,
1569
- # <tt>belongs_to :favorite_person, class_name: "Person"</tt> will use a foreign key
1570
- # of "favorite_person_id".
1571
- # [:foreign_type]
1572
- # Specify the column used to store the associated object's type, if this is a polymorphic
1573
- # association. By default this is guessed to be the name of the association with a "_type"
1574
- # suffix. So a class that defines a <tt>belongs_to :taggable, polymorphic: true</tt>
1575
- # association will use "taggable_type" as the default <tt>:foreign_type</tt>.
1576
- # [:primary_key]
1577
- # Specify the method that returns the primary key of associated object used for the association.
1578
- # By default this is id.
1579
- # [:dependent]
1580
- # If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
1581
- # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
1582
- # This option should not be specified when #belongs_to is used in conjunction with
1583
- # a #has_many relationship on another class because of the potential to leave
1584
- # orphaned records behind.
1585
- # [:counter_cache]
1586
- # Caches the number of belonging objects on the associate class through the use of CounterCache::ClassMethods#increment_counter
1587
- # and CounterCache::ClassMethods#decrement_counter. The counter cache is incremented when an object of this
1588
- # class is created and decremented when it's destroyed. This requires that a column
1589
- # named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
1590
- # is used on the associate class (such as a Post class) - that is the migration for
1591
- # <tt>#{table_name}_count</tt> is created on the associate class (such that <tt>Post.comments_count</tt> will
1592
- # return the count cached, see note below). You can also specify a custom counter
1593
- # cache column by providing a column name instead of a +true+/+false+ value to this
1594
- # option (e.g., <tt>counter_cache: :my_custom_counter</tt>.)
1595
- # Note: Specifying a counter cache will add it to that model's list of readonly attributes
1596
- # using +attr_readonly+.
1597
- # [:polymorphic]
1598
- # Specify this association is a polymorphic association by passing +true+.
1599
- # Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
1600
- # to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
1601
- # [:validate]
1602
- # When set to +true+, validates new objects added to association when saving the parent object. +false+ by default.
1603
- # If you want to ensure associated objects are revalidated on every update, use +validates_associated+.
1604
- # [:autosave]
1605
- # If true, always save the associated object or destroy it if marked for destruction, when
1606
- # saving the parent object.
1607
- # If false, never save or destroy the associated object.
1608
- # By default, only save the associated object if it's a new record.
1609
- #
1610
- # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for
1611
- # sets <tt>:autosave</tt> to <tt>true</tt>.
1612
- # [:touch]
1613
- # If true, the associated object will be touched (the updated_at/on attributes set to current time)
1614
- # when this record is either saved or destroyed. If you specify a symbol, that attribute
1615
- # will be updated with the current time in addition to the updated_at/on attribute.
1616
- # Please note that with touching no validation is performed and only the +after_touch+,
1617
- # +after_commit+ and +after_rollback+ callbacks are executed.
1618
- # [:inverse_of]
1619
- # Specifies the name of the #has_one or #has_many association on the associated
1620
- # object that is the inverse of this #belongs_to association. Does not work in
1621
- # combination with the <tt>:polymorphic</tt> options.
1622
- # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
1623
- # [:optional]
1624
- # When set to +true+, the association will not have its presence validated.
1625
- # [:required]
1626
- # When set to +true+, the association will also have its presence validated.
1627
- # This will validate the association itself, not the id. You can use
1628
- # +:inverse_of+ to avoid an extra query during validation.
1629
- # NOTE: <tt>required</tt> is set to <tt>true</tt> by default and is deprecated. If
1630
- # you don't want to have association presence validated, use <tt>optional: true</tt>.
1631
- #
1632
- # Option examples:
1633
- # belongs_to :firm, foreign_key: "client_of"
1634
- # belongs_to :person, primary_key: "name", foreign_key: "person_name"
1635
- # belongs_to :author, class_name: "Person", foreign_key: "author_id"
1636
- # belongs_to :valid_coupon, ->(o) { where "discounts > ?", o.payments_count },
1637
- # class_name: "Coupon", foreign_key: "coupon_id"
1638
- # belongs_to :attachable, polymorphic: true
1639
- # belongs_to :project, -> { readonly }
1640
- # belongs_to :post, counter_cache: true
1641
- # belongs_to :comment, touch: true
1642
- # belongs_to :company, touch: :employees_last_updated_at
1643
- # belongs_to :user, optional: true
1644
- def belongs_to(name, scope = nil, options = {})
1645
- reflection = Builder::BelongsTo.build(self, name, scope, options)
1646
- Reflection.add_reflection self, name, reflection
1647
- end
1648
-
1649
- # Specifies a many-to-many relationship with another class. This associates two classes via an
1650
- # intermediate join table. Unless the join table is explicitly specified as an option, it is
1651
- # guessed using the lexical order of the class names. So a join between Developer and Project
1652
- # will give the default join table name of "developers_projects" because "D" precedes "P" alphabetically.
1653
- # Note that this precedence is calculated using the <tt><</tt> operator for String. This
1654
- # means that if the strings are of different lengths, and the strings are equal when compared
1655
- # up to the shortest length, then the longer string is considered of higher
1656
- # lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers"
1657
- # to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes",
1658
- # but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the
1659
- # custom <tt>:join_table</tt> option if you need to.
1660
- # If your tables share a common prefix, it will only appear once at the beginning. For example,
1661
- # the tables "catalog_categories" and "catalog_products" generate a join table name of "catalog_categories_products".
1662
- #
1663
- # The join table should not have a primary key or a model associated with it. You must manually generate the
1664
- # join table with a migration such as this:
1665
- #
1666
- # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration[5.0]
1667
- # def change
1668
- # create_join_table :developers, :projects
398
+ # The association methods module is included immediately after the
399
+ # generated attributes methods module, meaning an association will
400
+ # override the methods for an attribute with the same name.
401
+ #
402
+ # == Cardinality and associations
403
+ #
404
+ # Active Record associations can be used to describe one-to-one, one-to-many and many-to-many
405
+ # relationships between models. Each model uses an association to describe its role in
406
+ # the relation. The #belongs_to association is always used in the model that has
407
+ # the foreign key.
408
+ #
409
+ # === One-to-one
410
+ #
411
+ # Use #has_one in the base, and #belongs_to in the associated model.
412
+ #
413
+ # class Employee < ActiveRecord::Base
414
+ # has_one :office
415
+ # end
416
+ # class Office < ActiveRecord::Base
417
+ # belongs_to :employee # foreign key - employee_id
418
+ # end
419
+ #
420
+ # === One-to-many
421
+ #
422
+ # Use #has_many in the base, and #belongs_to in the associated model.
423
+ #
424
+ # class Manager < ActiveRecord::Base
425
+ # has_many :employees
426
+ # end
427
+ # class Employee < ActiveRecord::Base
428
+ # belongs_to :manager # foreign key - manager_id
429
+ # end
430
+ #
431
+ # === Many-to-many
432
+ #
433
+ # There are two ways to build a many-to-many relationship.
434
+ #
435
+ # The first way uses a #has_many association with the <tt>:through</tt> option and a join model, so
436
+ # there are two stages of associations.
437
+ #
438
+ # class Assignment < ActiveRecord::Base
439
+ # belongs_to :programmer # foreign key - programmer_id
440
+ # belongs_to :project # foreign key - project_id
441
+ # end
442
+ # class Programmer < ActiveRecord::Base
443
+ # has_many :assignments
444
+ # has_many :projects, through: :assignments
445
+ # end
446
+ # class Project < ActiveRecord::Base
447
+ # has_many :assignments
448
+ # has_many :programmers, through: :assignments
449
+ # end
450
+ #
451
+ # For the second way, use #has_and_belongs_to_many in both models. This requires a join table
452
+ # that has no corresponding model or primary key.
453
+ #
454
+ # class Programmer < ActiveRecord::Base
455
+ # has_and_belongs_to_many :projects # foreign keys in the join table
456
+ # end
457
+ # class Project < ActiveRecord::Base
458
+ # has_and_belongs_to_many :programmers # foreign keys in the join table
459
+ # end
460
+ #
461
+ # Choosing which way to build a many-to-many relationship is not always simple.
462
+ # If you need to work with the relationship model as its own entity,
463
+ # use #has_many <tt>:through</tt>. Use #has_and_belongs_to_many when working with legacy schemas or when
464
+ # you never work directly with the relationship itself.
465
+ #
466
+ # == Is it a #belongs_to or #has_one association?
467
+ #
468
+ # Both express a 1-1 relationship. The difference is mostly where to place the foreign
469
+ # key, which goes on the table for the class declaring the #belongs_to relationship.
470
+ #
471
+ # class User < ActiveRecord::Base
472
+ # # I reference an account.
473
+ # belongs_to :account
474
+ # end
475
+ #
476
+ # class Account < ActiveRecord::Base
477
+ # # One user references me.
478
+ # has_one :user
479
+ # end
480
+ #
481
+ # The tables for these classes could look something like:
482
+ #
483
+ # CREATE TABLE users (
484
+ # id int NOT NULL auto_increment,
485
+ # account_id int default NULL,
486
+ # name varchar default NULL,
487
+ # PRIMARY KEY (id)
488
+ # )
489
+ #
490
+ # CREATE TABLE accounts (
491
+ # id int NOT NULL auto_increment,
492
+ # name varchar default NULL,
493
+ # PRIMARY KEY (id)
494
+ # )
495
+ #
496
+ # == Unsaved objects and associations
497
+ #
498
+ # You can manipulate objects and associations before they are saved to the database, but
499
+ # there is some special behavior you should be aware of, mostly involving the saving of
500
+ # associated objects.
501
+ #
502
+ # You can set the <tt>:autosave</tt> option on a #has_one, #belongs_to,
503
+ # #has_many, or #has_and_belongs_to_many association. Setting it
504
+ # to +true+ will _always_ save the members, whereas setting it to +false+ will
505
+ # _never_ save the members. More details about <tt>:autosave</tt> option is available at
506
+ # AutosaveAssociation.
507
+ #
508
+ # === One-to-one associations
509
+ #
510
+ # * Assigning an object to a #has_one association automatically saves that object and
511
+ # the object being replaced (if there is one), in order to update their foreign
512
+ # keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
513
+ # * If either of these saves fail (due to one of the objects being invalid), an
514
+ # ActiveRecord::RecordNotSaved exception is raised and the assignment is
515
+ # cancelled.
516
+ # * If you wish to assign an object to a #has_one association without saving it,
517
+ # use the <tt>#build_association</tt> method (documented below). The object being
518
+ # replaced will still be saved to update its foreign key.
519
+ # * Assigning an object to a #belongs_to association does not save the object, since
520
+ # the foreign key field belongs on the parent. It does not save the parent either.
521
+ #
522
+ # === Collections
523
+ #
524
+ # * Adding an object to a collection (#has_many or #has_and_belongs_to_many) automatically
525
+ # saves that object, except if the parent object (the owner of the collection) is not yet
526
+ # stored in the database.
527
+ # * If saving any of the objects being added to a collection (via <tt>push</tt> or similar)
528
+ # fails, then <tt>push</tt> returns +false+.
529
+ # * If saving fails while replacing the collection (via <tt>association=</tt>), an
530
+ # ActiveRecord::RecordNotSaved exception is raised and the assignment is
531
+ # cancelled.
532
+ # * You can add an object to a collection without automatically saving it by using the
533
+ # <tt>collection.build</tt> method (documented below).
534
+ # * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically
535
+ # saved when the parent is saved.
536
+ #
537
+ # == Customizing the query
538
+ #
539
+ # \Associations are built from <tt>Relation</tt> objects, and you can use the Relation syntax
540
+ # to customize them. For example, to add a condition:
541
+ #
542
+ # class Blog < ActiveRecord::Base
543
+ # has_many :published_posts, -> { where(published: true) }, class_name: 'Post'
544
+ # end
545
+ #
546
+ # Inside the <tt>-> { ... }</tt> block you can use all of the usual Relation methods.
547
+ #
548
+ # === Accessing the owner object
549
+ #
550
+ # Sometimes it is useful to have access to the owner object when building the query. The owner
551
+ # is passed as a parameter to the block. For example, the following association would find all
552
+ # events that occur on the user's birthday:
553
+ #
554
+ # class User < ActiveRecord::Base
555
+ # has_many :birthday_events, ->(user) { where(starts_on: user.birthday) }, class_name: 'Event'
556
+ # end
557
+ #
558
+ # Note: Joining, eager loading and preloading of these associations is not fully possible.
559
+ # These operations happen before instance creation and the scope will be called with a +nil+ argument.
560
+ # This can lead to unexpected behavior and is deprecated.
561
+ #
562
+ # == Association callbacks
563
+ #
564
+ # Similar to the normal callbacks that hook into the life cycle of an Active Record object,
565
+ # you can also define callbacks that get triggered when you add an object to or remove an
566
+ # object from an association collection.
567
+ #
568
+ # class Project
569
+ # has_and_belongs_to_many :developers, after_add: :evaluate_velocity
570
+ #
571
+ # def evaluate_velocity(developer)
572
+ # ...
1669
573
  # end
1670
574
  # end
1671
575
  #
1672
- # It's also a good idea to add indexes to each of those columns to speed up the joins process.
1673
- # However, in MySQL it is advised to add a compound index for both of the columns as MySQL only
1674
- # uses one index per table during the lookup.
1675
- #
1676
- # Adds the following methods for retrieval and query:
1677
- #
1678
- # +collection+ is a placeholder for the symbol passed as the +name+ argument, so
1679
- # <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.
1680
- #
1681
- # [collection]
1682
- # Returns a Relation of all the associated objects.
1683
- # An empty Relation is returned if none are found.
1684
- # [collection<<(object, ...)]
1685
- # Adds one or more objects to the collection by creating associations in the join table
1686
- # (<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to this method).
1687
- # Note that this operation instantly fires update SQL without waiting for the save or update call on the
1688
- # parent object, unless the parent object is a new record.
1689
- # [collection.delete(object, ...)]
1690
- # Removes one or more objects from the collection by removing their associations from the join table.
1691
- # This does not destroy the objects.
1692
- # [collection.destroy(object, ...)]
1693
- # Removes one or more objects from the collection by running destroy on each association in the join table, overriding any dependent option.
1694
- # This does not destroy the objects.
1695
- # [collection=objects]
1696
- # Replaces the collection's content by deleting and adding objects as appropriate.
1697
- # [collection_singular_ids]
1698
- # Returns an array of the associated objects' ids.
1699
- # [collection_singular_ids=ids]
1700
- # Replace the collection by the objects identified by the primary keys in +ids+.
1701
- # [collection.clear]
1702
- # Removes every object from the collection. This does not destroy the objects.
1703
- # [collection.empty?]
1704
- # Returns +true+ if there are no associated objects.
1705
- # [collection.size]
1706
- # Returns the number of associated objects.
1707
- # [collection.find(id)]
1708
- # Finds an associated object responding to the +id+ and that
1709
- # meets the condition that it has to be associated with this object.
1710
- # Uses the same rules as ActiveRecord::FinderMethods#find.
1711
- # [collection.exists?(...)]
1712
- # Checks whether an associated object with the given conditions exists.
1713
- # Uses the same rules as ActiveRecord::FinderMethods#exists?.
1714
- # [collection.build(attributes = {})]
1715
- # Returns a new object of the collection type that has been instantiated
1716
- # with +attributes+ and linked to this object through the join table, but has not yet been saved.
1717
- # [collection.create(attributes = {})]
1718
- # Returns a new object of the collection type that has been instantiated
1719
- # with +attributes+, linked to this object through the join table, and that has already been
1720
- # saved (if it passed the validation).
1721
- # [collection.reload]
1722
- # Returns a Relation of all of the associated objects, forcing a database read.
1723
- # An empty Relation is returned if none are found.
1724
- #
1725
- # === Example
1726
- #
1727
- # A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
1728
- # * <tt>Developer#projects</tt>
1729
- # * <tt>Developer#projects<<</tt>
1730
- # * <tt>Developer#projects.delete</tt>
1731
- # * <tt>Developer#projects.destroy</tt>
1732
- # * <tt>Developer#projects=</tt>
1733
- # * <tt>Developer#project_ids</tt>
1734
- # * <tt>Developer#project_ids=</tt>
1735
- # * <tt>Developer#projects.clear</tt>
1736
- # * <tt>Developer#projects.empty?</tt>
1737
- # * <tt>Developer#projects.size</tt>
1738
- # * <tt>Developer#projects.find(id)</tt>
1739
- # * <tt>Developer#projects.exists?(...)</tt>
1740
- # * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("developer_id" => id)</tt>)
1741
- # * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("developer_id" => id); c.save; c</tt>)
1742
- # * <tt>Developer#projects.reload</tt>
1743
- # The declaration may include an +options+ hash to specialize the behavior of the association.
1744
- #
1745
- # === Scopes
1746
- #
1747
- # You can pass a second argument +scope+ as a callable (i.e. proc or
1748
- # lambda) to retrieve a specific set of records or customize the generated
1749
- # query when you access the associated collection.
1750
- #
1751
- # Scope examples:
1752
- # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) }
1753
- # has_and_belongs_to_many :categories, ->(category) {
1754
- # where("default_category = ?", category.name)
1755
- # }
1756
- #
1757
- # === Extensions
1758
- #
1759
- # The +extension+ argument allows you to pass a block into a
1760
- # has_and_belongs_to_many association. This is useful for adding new
1761
- # finders, creators and other factory-type methods to be used as part of
1762
- # the association.
1763
- #
1764
- # Extension examples:
1765
- # has_and_belongs_to_many :contractors do
576
+ # It's possible to stack callbacks by passing them as an array. Example:
577
+ #
578
+ # class Project
579
+ # has_and_belongs_to_many :developers,
580
+ # after_add: [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
581
+ # end
582
+ #
583
+ # Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+.
584
+ #
585
+ # If any of the +before_add+ callbacks throw an exception, the object will not be
586
+ # added to the collection.
587
+ #
588
+ # Similarly, if any of the +before_remove+ callbacks throw an exception, the object
589
+ # will not be removed from the collection.
590
+ #
591
+ # == Association extensions
592
+ #
593
+ # The proxy objects that control the access to associations can be extended through anonymous
594
+ # modules. This is especially beneficial for adding new finders, creators, and other
595
+ # factory-type methods that are only used as part of this association.
596
+ #
597
+ # class Account < ActiveRecord::Base
598
+ # has_many :people do
599
+ # def find_or_create_by_name(name)
600
+ # first_name, last_name = name.split(" ", 2)
601
+ # find_or_create_by(first_name: first_name, last_name: last_name)
602
+ # end
603
+ # end
604
+ # end
605
+ #
606
+ # person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson")
607
+ # person.first_name # => "David"
608
+ # person.last_name # => "Heinemeier Hansson"
609
+ #
610
+ # If you need to share the same extensions between many associations, you can use a named
611
+ # extension module.
612
+ #
613
+ # module FindOrCreateByNameExtension
1766
614
  # def find_or_create_by_name(name)
1767
615
  # first_name, last_name = name.split(" ", 2)
1768
616
  # find_or_create_by(first_name: first_name, last_name: last_name)
1769
617
  # end
1770
618
  # end
1771
619
  #
1772
- # === Options
1773
- #
1774
- # [:class_name]
1775
- # Specify the class name of the association. Use it only if that name can't be inferred
1776
- # from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
1777
- # Project class, but if the real class name is SuperProject, you'll have to specify it with this option.
1778
- # [:join_table]
1779
- # Specify the name of the join table if the default based on lexical order isn't what you want.
1780
- # <b>WARNING:</b> If you're overwriting the table name of either class, the +table_name+ method
1781
- # MUST be declared underneath any #has_and_belongs_to_many declaration in order to work.
1782
- # [:foreign_key]
1783
- # Specify the foreign key used for the association. By default this is guessed to be the name
1784
- # of this class in lower-case and "_id" suffixed. So a Person class that makes
1785
- # a #has_and_belongs_to_many association to Project will use "person_id" as the
1786
- # default <tt>:foreign_key</tt>.
1787
- # [:association_foreign_key]
1788
- # Specify the foreign key used for the association on the receiving side of the association.
1789
- # By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
1790
- # So if a Person class makes a #has_and_belongs_to_many association to Project,
1791
- # the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
1792
- # [:validate]
1793
- # When set to +true+, validates new objects added to association when saving the parent object. +true+ by default.
1794
- # If you want to ensure associated objects are revalidated on every update, use +validates_associated+.
1795
- # [:autosave]
1796
- # If true, always save the associated objects or destroy them if marked for destruction, when
1797
- # saving the parent object.
1798
- # If false, never save or destroy the associated objects.
1799
- # By default, only save associated objects that are new records.
1800
- #
1801
- # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets
1802
- # <tt>:autosave</tt> to <tt>true</tt>.
1803
- #
1804
- # Option examples:
1805
- # has_and_belongs_to_many :projects
1806
- # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) }
1807
- # has_and_belongs_to_many :nations, class_name: "Country"
1808
- # has_and_belongs_to_many :categories, join_table: "prods_cats"
1809
- # has_and_belongs_to_many :categories, -> { readonly }
1810
- def has_and_belongs_to_many(name, scope = nil, options = {}, &extension)
1811
- if scope.is_a?(Hash)
1812
- options = scope
1813
- scope = nil
620
+ # class Account < ActiveRecord::Base
621
+ # has_many :people, -> { extending FindOrCreateByNameExtension }
622
+ # end
623
+ #
624
+ # class Company < ActiveRecord::Base
625
+ # has_many :people, -> { extending FindOrCreateByNameExtension }
626
+ # end
627
+ #
628
+ # Some extensions can only be made to work with knowledge of the association's internals.
629
+ # Extensions can access relevant state using the following methods (where +items+ is the
630
+ # name of the association):
631
+ #
632
+ # * <tt>record.association(:items).owner</tt> - Returns the object the association is part of.
633
+ # * <tt>record.association(:items).reflection</tt> - Returns the reflection object that describes the association.
634
+ # * <tt>record.association(:items).target</tt> - Returns the associated object for #belongs_to and #has_one, or
635
+ # the collection of associated objects for #has_many and #has_and_belongs_to_many.
636
+ #
637
+ # However, inside the actual extension code, you will not have access to the <tt>record</tt> as
638
+ # above. In this case, you can access <tt>proxy_association</tt>. For example,
639
+ # <tt>record.association(:items)</tt> and <tt>record.items.proxy_association</tt> will return
640
+ # the same object, allowing you to make calls like <tt>proxy_association.owner</tt> inside
641
+ # association extensions.
642
+ #
643
+ # == Association Join Models
644
+ #
645
+ # Has Many associations can be configured with the <tt>:through</tt> option to use an
646
+ # explicit join model to retrieve the data. This operates similarly to a
647
+ # #has_and_belongs_to_many association. The advantage is that you're able to add validations,
648
+ # callbacks, and extra attributes on the join model. Consider the following schema:
649
+ #
650
+ # class Author < ActiveRecord::Base
651
+ # has_many :authorships
652
+ # has_many :books, through: :authorships
653
+ # end
654
+ #
655
+ # class Authorship < ActiveRecord::Base
656
+ # belongs_to :author
657
+ # belongs_to :book
658
+ # end
659
+ #
660
+ # @author = Author.first
661
+ # @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to
662
+ # @author.books # selects all books by using the Authorship join model
663
+ #
664
+ # You can also go through a #has_many association on the join model:
665
+ #
666
+ # class Firm < ActiveRecord::Base
667
+ # has_many :clients
668
+ # has_many :invoices, through: :clients
669
+ # end
670
+ #
671
+ # class Client < ActiveRecord::Base
672
+ # belongs_to :firm
673
+ # has_many :invoices
674
+ # end
675
+ #
676
+ # class Invoice < ActiveRecord::Base
677
+ # belongs_to :client
678
+ # end
679
+ #
680
+ # @firm = Firm.first
681
+ # @firm.clients.flat_map { |c| c.invoices } # select all invoices for all clients of the firm
682
+ # @firm.invoices # selects all invoices by going through the Client join model
683
+ #
684
+ # Similarly you can go through a #has_one association on the join model:
685
+ #
686
+ # class Group < ActiveRecord::Base
687
+ # has_many :users
688
+ # has_many :avatars, through: :users
689
+ # end
690
+ #
691
+ # class User < ActiveRecord::Base
692
+ # belongs_to :group
693
+ # has_one :avatar
694
+ # end
695
+ #
696
+ # class Avatar < ActiveRecord::Base
697
+ # belongs_to :user
698
+ # end
699
+ #
700
+ # @group = Group.first
701
+ # @group.users.collect { |u| u.avatar }.compact # select all avatars for all users in the group
702
+ # @group.avatars # selects all avatars by going through the User join model.
703
+ #
704
+ # An important caveat with going through #has_one or #has_many associations on the
705
+ # join model is that these associations are *read-only*. For example, the following
706
+ # would not work following the previous example:
707
+ #
708
+ # @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around
709
+ # @group.avatars.delete(@group.avatars.last) # so would this
710
+ #
711
+ # == Setting Inverses
712
+ #
713
+ # If you are using a #belongs_to on the join model, it is a good idea to set the
714
+ # <tt>:inverse_of</tt> option on the #belongs_to, which will mean that the following example
715
+ # works correctly (where <tt>tags</tt> is a #has_many <tt>:through</tt> association):
716
+ #
717
+ # @post = Post.first
718
+ # @tag = @post.tags.build name: "ruby"
719
+ # @tag.save
720
+ #
721
+ # The last line ought to save the through record (a <tt>Tagging</tt>). This will only work if the
722
+ # <tt>:inverse_of</tt> is set:
723
+ #
724
+ # class Tagging < ActiveRecord::Base
725
+ # belongs_to :post
726
+ # belongs_to :tag, inverse_of: :taggings
727
+ # end
728
+ #
729
+ # If you do not set the <tt>:inverse_of</tt> record, the association will
730
+ # do its best to match itself up with the correct inverse. Automatic
731
+ # inverse detection only works on #has_many, #has_one, and
732
+ # #belongs_to associations.
733
+ #
734
+ # Extra options on the associations, as defined in the
735
+ # <tt>AssociationReflection::INVALID_AUTOMATIC_INVERSE_OPTIONS</tt> constant, will
736
+ # also prevent the association's inverse from being found automatically.
737
+ #
738
+ # The automatic guessing of the inverse association uses a heuristic based
739
+ # on the name of the class, so it may not work for all associations,
740
+ # especially the ones with non-standard names.
741
+ #
742
+ # You can turn off the automatic detection of inverse associations by setting
743
+ # the <tt>:inverse_of</tt> option to <tt>false</tt> like so:
744
+ #
745
+ # class Tagging < ActiveRecord::Base
746
+ # belongs_to :tag, inverse_of: false
747
+ # end
748
+ #
749
+ # == Nested \Associations
750
+ #
751
+ # You can actually specify *any* association with the <tt>:through</tt> option, including an
752
+ # association which has a <tt>:through</tt> option itself. For example:
753
+ #
754
+ # class Author < ActiveRecord::Base
755
+ # has_many :posts
756
+ # has_many :comments, through: :posts
757
+ # has_many :commenters, through: :comments
758
+ # end
759
+ #
760
+ # class Post < ActiveRecord::Base
761
+ # has_many :comments
762
+ # end
763
+ #
764
+ # class Comment < ActiveRecord::Base
765
+ # belongs_to :commenter
766
+ # end
767
+ #
768
+ # @author = Author.first
769
+ # @author.commenters # => People who commented on posts written by the author
770
+ #
771
+ # An equivalent way of setting up this association this would be:
772
+ #
773
+ # class Author < ActiveRecord::Base
774
+ # has_many :posts
775
+ # has_many :commenters, through: :posts
776
+ # end
777
+ #
778
+ # class Post < ActiveRecord::Base
779
+ # has_many :comments
780
+ # has_many :commenters, through: :comments
781
+ # end
782
+ #
783
+ # class Comment < ActiveRecord::Base
784
+ # belongs_to :commenter
785
+ # end
786
+ #
787
+ # When using a nested association, you will not be able to modify the association because there
788
+ # is not enough information to know what modification to make. For example, if you tried to
789
+ # add a <tt>Commenter</tt> in the example above, there would be no way to tell how to set up the
790
+ # intermediate <tt>Post</tt> and <tt>Comment</tt> objects.
791
+ #
792
+ # == Polymorphic \Associations
793
+ #
794
+ # Polymorphic associations on models are not restricted on what types of models they
795
+ # can be associated with. Rather, they specify an interface that a #has_many association
796
+ # must adhere to.
797
+ #
798
+ # class Asset < ActiveRecord::Base
799
+ # belongs_to :attachable, polymorphic: true
800
+ # end
801
+ #
802
+ # class Post < ActiveRecord::Base
803
+ # has_many :assets, as: :attachable # The :as option specifies the polymorphic interface to use.
804
+ # end
805
+ #
806
+ # @asset.attachable = @post
807
+ #
808
+ # This works by using a type column in addition to a foreign key to specify the associated
809
+ # record. In the Asset example, you'd need an +attachable_id+ integer column and an
810
+ # +attachable_type+ string column.
811
+ #
812
+ # Using polymorphic associations in combination with single table inheritance (STI) is
813
+ # a little tricky. In order for the associations to work as expected, ensure that you
814
+ # store the base model for the STI models in the type column of the polymorphic
815
+ # association. To continue with the asset example above, suppose there are guest posts
816
+ # and member posts that use the posts table for STI. In this case, there must be a +type+
817
+ # column in the posts table.
818
+ #
819
+ # Note: The <tt>attachable_type=</tt> method is being called when assigning an +attachable+.
820
+ # The +class_name+ of the +attachable+ is passed as a String.
821
+ #
822
+ # class Asset < ActiveRecord::Base
823
+ # belongs_to :attachable, polymorphic: true
824
+ #
825
+ # def attachable_type=(class_name)
826
+ # super(class_name.constantize.base_class.to_s)
827
+ # end
828
+ # end
829
+ #
830
+ # class Post < ActiveRecord::Base
831
+ # # because we store "Post" in attachable_type now dependent: :destroy will work
832
+ # has_many :assets, as: :attachable, dependent: :destroy
833
+ # end
834
+ #
835
+ # class GuestPost < Post
836
+ # end
837
+ #
838
+ # class MemberPost < Post
839
+ # end
840
+ #
841
+ # == Caching
842
+ #
843
+ # All of the methods are built on a simple caching principle that will keep the result
844
+ # of the last query around unless specifically instructed not to. The cache is even
845
+ # shared across methods to make it even cheaper to use the macro-added methods without
846
+ # worrying too much about performance at the first go.
847
+ #
848
+ # project.milestones # fetches milestones from the database
849
+ # project.milestones.size # uses the milestone cache
850
+ # project.milestones.empty? # uses the milestone cache
851
+ # project.milestones(true).size # fetches milestones from the database
852
+ # project.milestones # uses the milestone cache
853
+ #
854
+ # == Eager loading of associations
855
+ #
856
+ # Eager loading is a way to find objects of a certain class and a number of named associations.
857
+ # It is one of the easiest ways to prevent the dreaded N+1 problem in which fetching 100
858
+ # posts that each need to display their author triggers 101 database queries. Through the
859
+ # use of eager loading, the number of queries will be reduced from 101 to 2.
860
+ #
861
+ # class Post < ActiveRecord::Base
862
+ # belongs_to :author
863
+ # has_many :comments
864
+ # end
865
+ #
866
+ # Consider the following loop using the class above:
867
+ #
868
+ # Post.all.each do |post|
869
+ # puts "Post: " + post.title
870
+ # puts "Written by: " + post.author.name
871
+ # puts "Last comment on: " + post.comments.first.created_on
872
+ # end
873
+ #
874
+ # To iterate over these one hundred posts, we'll generate 201 database queries. Let's
875
+ # first just optimize it for retrieving the author:
876
+ #
877
+ # Post.includes(:author).each do |post|
878
+ #
879
+ # This references the name of the #belongs_to association that also used the <tt>:author</tt>
880
+ # symbol. After loading the posts, +find+ will collect the +author_id+ from each one and load
881
+ # all of the referenced authors with one query. Doing so will cut down the number of queries
882
+ # from 201 to 102.
883
+ #
884
+ # We can improve upon the situation further by referencing both associations in the finder with:
885
+ #
886
+ # Post.includes(:author, :comments).each do |post|
887
+ #
888
+ # This will load all comments with a single query. This reduces the total number of queries
889
+ # to 3. In general, the number of queries will be 1 plus the number of associations
890
+ # named (except if some of the associations are polymorphic #belongs_to - see below).
891
+ #
892
+ # To include a deep hierarchy of associations, use a hash:
893
+ #
894
+ # Post.includes(:author, { comments: { author: :gravatar } }).each do |post|
895
+ #
896
+ # The above code will load all the comments and all of their associated
897
+ # authors and gravatars. You can mix and match any combination of symbols,
898
+ # arrays, and hashes to retrieve the associations you want to load.
899
+ #
900
+ # All of this power shouldn't fool you into thinking that you can pull out huge amounts
901
+ # of data with no performance penalty just because you've reduced the number of queries.
902
+ # The database still needs to send all the data to Active Record and it still needs to
903
+ # be processed. So it's no catch-all for performance problems, but it's a great way to
904
+ # cut down on the number of queries in a situation as the one described above.
905
+ #
906
+ # Since only one table is loaded at a time, conditions or orders cannot reference tables
907
+ # other than the main one. If this is the case, Active Record falls back to the previously
908
+ # used <tt>LEFT OUTER JOIN</tt> based strategy. For example:
909
+ #
910
+ # Post.includes([:author, :comments]).where(['comments.approved = ?', true])
911
+ #
912
+ # This will result in a single SQL query with joins along the lines of:
913
+ # <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
914
+ # <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions
915
+ # like this can have unintended consequences.
916
+ # In the above example, posts with no approved comments are not returned at all because
917
+ # the conditions apply to the SQL statement as a whole and not just to the association.
918
+ #
919
+ # You must disambiguate column references for this fallback to happen, for example
920
+ # <tt>order: "author.name DESC"</tt> will work but <tt>order: "name DESC"</tt> will not.
921
+ #
922
+ # If you want to load all posts (including posts with no approved comments), then write
923
+ # your own <tt>LEFT OUTER JOIN</tt> query using <tt>ON</tt>:
924
+ #
925
+ # Post.joins("LEFT OUTER JOIN comments ON comments.post_id = posts.id AND comments.approved = '1'")
926
+ #
927
+ # In this case, it is usually more natural to include an association which has conditions defined on it:
928
+ #
929
+ # class Post < ActiveRecord::Base
930
+ # has_many :approved_comments, -> { where(approved: true) }, class_name: 'Comment'
931
+ # end
932
+ #
933
+ # Post.includes(:approved_comments)
934
+ #
935
+ # This will load posts and eager load the +approved_comments+ association, which contains
936
+ # only those comments that have been approved.
937
+ #
938
+ # If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored,
939
+ # returning all the associated objects:
940
+ #
941
+ # class Picture < ActiveRecord::Base
942
+ # has_many :most_recent_comments, -> { order('id DESC').limit(10) }, class_name: 'Comment'
943
+ # end
944
+ #
945
+ # Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments.
946
+ #
947
+ # Eager loading is supported with polymorphic associations.
948
+ #
949
+ # class Address < ActiveRecord::Base
950
+ # belongs_to :addressable, polymorphic: true
951
+ # end
952
+ #
953
+ # A call that tries to eager load the addressable model
954
+ #
955
+ # Address.includes(:addressable)
956
+ #
957
+ # This will execute one query to load the addresses and load the addressables with one
958
+ # query per addressable type.
959
+ # For example, if all the addressables are either of class Person or Company, then a total
960
+ # of 3 queries will be executed. The list of addressable types to load is determined on
961
+ # the back of the addresses loaded. This is not supported if Active Record has to fallback
962
+ # to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError.
963
+ # The reason is that the parent model's type is a column value so its corresponding table
964
+ # name cannot be put in the +FROM+/+JOIN+ clauses of that query.
965
+ #
966
+ # == Table Aliasing
967
+ #
968
+ # Active Record uses table aliasing in the case that a table is referenced multiple times
969
+ # in a join. If a table is referenced only once, the standard table name is used. The
970
+ # second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>.
971
+ # Indexes are appended for any more successive uses of the table name.
972
+ #
973
+ # Post.joins(:comments)
974
+ # # => SELECT ... FROM posts INNER JOIN comments ON ...
975
+ # Post.joins(:special_comments) # STI
976
+ # # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment'
977
+ # Post.joins(:comments, :special_comments) # special_comments is the reflection name, posts is the parent table name
978
+ # # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts
979
+ #
980
+ # Acts as tree example:
981
+ #
982
+ # TreeMixin.joins(:children)
983
+ # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
984
+ # TreeMixin.joins(children: :parent)
985
+ # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
986
+ # INNER JOIN parents_mixins ...
987
+ # TreeMixin.joins(children: {parent: :children})
988
+ # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
989
+ # INNER JOIN parents_mixins ...
990
+ # INNER JOIN mixins childrens_mixins_2
991
+ #
992
+ # Has and Belongs to Many join tables use the same idea, but add a <tt>_join</tt> suffix:
993
+ #
994
+ # Post.joins(:categories)
995
+ # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
996
+ # Post.joins(categories: :posts)
997
+ # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
998
+ # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
999
+ # Post.joins(categories: {posts: :categories})
1000
+ # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
1001
+ # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
1002
+ # INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
1003
+ #
1004
+ # If you wish to specify your own custom joins using ActiveRecord::QueryMethods#joins method, those table
1005
+ # names will take precedence over the eager associations:
1006
+ #
1007
+ # Post.joins(:comments).joins("inner join comments ...")
1008
+ # # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...
1009
+ # Post.joins(:comments, :special_comments).joins("inner join comments ...")
1010
+ # # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ...
1011
+ # INNER JOIN comments special_comments_posts ...
1012
+ # INNER JOIN comments ...
1013
+ #
1014
+ # Table aliases are automatically truncated according to the maximum length of table identifiers
1015
+ # according to the specific database.
1016
+ #
1017
+ # == Modules
1018
+ #
1019
+ # By default, associations will look for objects within the current module scope. Consider:
1020
+ #
1021
+ # module MyApplication
1022
+ # module Business
1023
+ # class Firm < ActiveRecord::Base
1024
+ # has_many :clients
1025
+ # end
1026
+ #
1027
+ # class Client < ActiveRecord::Base; end
1028
+ # end
1029
+ # end
1030
+ #
1031
+ # When <tt>Firm#clients</tt> is called, it will in turn call
1032
+ # <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>.
1033
+ # If you want to associate with a class in another module scope, this can be done by
1034
+ # specifying the complete class name.
1035
+ #
1036
+ # module MyApplication
1037
+ # module Business
1038
+ # class Firm < ActiveRecord::Base; end
1039
+ # end
1040
+ #
1041
+ # module Billing
1042
+ # class Account < ActiveRecord::Base
1043
+ # belongs_to :firm, class_name: "MyApplication::Business::Firm"
1044
+ # end
1045
+ # end
1046
+ # end
1047
+ #
1048
+ # == Bi-directional associations
1049
+ #
1050
+ # When you specify an association, there is usually an association on the associated model
1051
+ # that specifies the same relationship in reverse. For example, with the following models:
1052
+ #
1053
+ # class Dungeon < ActiveRecord::Base
1054
+ # has_many :traps
1055
+ # has_one :evil_wizard
1056
+ # end
1057
+ #
1058
+ # class Trap < ActiveRecord::Base
1059
+ # belongs_to :dungeon
1060
+ # end
1061
+ #
1062
+ # class EvilWizard < ActiveRecord::Base
1063
+ # belongs_to :dungeon
1064
+ # end
1065
+ #
1066
+ # The +traps+ association on +Dungeon+ and the +dungeon+ association on +Trap+ are
1067
+ # the inverse of each other, and the inverse of the +dungeon+ association on +EvilWizard+
1068
+ # is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
1069
+ # Active Record can guess the inverse of the association based on the name
1070
+ # of the class. The result is the following:
1071
+ #
1072
+ # d = Dungeon.first
1073
+ # t = d.traps.first
1074
+ # d.object_id == t.dungeon.object_id # => true
1075
+ #
1076
+ # The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to
1077
+ # the same in-memory instance since the association matches the name of the class.
1078
+ # The result would be the same if we added +:inverse_of+ to our model definitions:
1079
+ #
1080
+ # class Dungeon < ActiveRecord::Base
1081
+ # has_many :traps, inverse_of: :dungeon
1082
+ # has_one :evil_wizard, inverse_of: :dungeon
1083
+ # end
1084
+ #
1085
+ # class Trap < ActiveRecord::Base
1086
+ # belongs_to :dungeon, inverse_of: :traps
1087
+ # end
1088
+ #
1089
+ # class EvilWizard < ActiveRecord::Base
1090
+ # belongs_to :dungeon, inverse_of: :evil_wizard
1091
+ # end
1092
+ #
1093
+ # There are limitations to <tt>:inverse_of</tt> support:
1094
+ #
1095
+ # * does not work with <tt>:through</tt> associations.
1096
+ # * does not work with <tt>:polymorphic</tt> associations.
1097
+ # * inverse associations for #belongs_to associations #has_many are ignored.
1098
+ #
1099
+ # For more information, see the documentation for the +:inverse_of+ option.
1100
+ #
1101
+ # == Deleting from associations
1102
+ #
1103
+ # === Dependent associations
1104
+ #
1105
+ # #has_many, #has_one, and #belongs_to associations support the <tt>:dependent</tt> option.
1106
+ # This allows you to specify that associated records should be deleted when the owner is
1107
+ # deleted.
1108
+ #
1109
+ # For example:
1110
+ #
1111
+ # class Author
1112
+ # has_many :posts, dependent: :destroy
1113
+ # end
1114
+ # Author.find(1).destroy # => Will destroy all of the author's posts, too
1115
+ #
1116
+ # The <tt>:dependent</tt> option can have different values which specify how the deletion
1117
+ # is done. For more information, see the documentation for this option on the different
1118
+ # specific association types. When no option is given, the behavior is to do nothing
1119
+ # with the associated records when destroying a record.
1120
+ #
1121
+ # Note that <tt>:dependent</tt> is implemented using Rails' callback
1122
+ # system, which works by processing callbacks in order. Therefore, other
1123
+ # callbacks declared either before or after the <tt>:dependent</tt> option
1124
+ # can affect what it does.
1125
+ #
1126
+ # Note that <tt>:dependent</tt> option is ignored for #has_one <tt>:through</tt> associations.
1127
+ #
1128
+ # === Delete or destroy?
1129
+ #
1130
+ # #has_many and #has_and_belongs_to_many associations have the methods <tt>destroy</tt>,
1131
+ # <tt>delete</tt>, <tt>destroy_all</tt> and <tt>delete_all</tt>.
1132
+ #
1133
+ # For #has_and_belongs_to_many, <tt>delete</tt> and <tt>destroy</tt> are the same: they
1134
+ # cause the records in the join table to be removed.
1135
+ #
1136
+ # For #has_many, <tt>destroy</tt> and <tt>destroy_all</tt> will always call the <tt>destroy</tt> method of the
1137
+ # record(s) being removed so that callbacks are run. However <tt>delete</tt> and <tt>delete_all</tt> will either
1138
+ # do the deletion according to the strategy specified by the <tt>:dependent</tt> option, or
1139
+ # if no <tt>:dependent</tt> option is given, then it will follow the default strategy.
1140
+ # The default strategy is to do nothing (leave the foreign keys with the parent ids set), except for
1141
+ # #has_many <tt>:through</tt>, where the default strategy is <tt>delete_all</tt> (delete
1142
+ # the join records, without running their callbacks).
1143
+ #
1144
+ # There is also a <tt>clear</tt> method which is the same as <tt>delete_all</tt>, except that
1145
+ # it returns the association rather than the records which have been deleted.
1146
+ #
1147
+ # === What gets deleted?
1148
+ #
1149
+ # There is a potential pitfall here: #has_and_belongs_to_many and #has_many <tt>:through</tt>
1150
+ # associations have records in join tables, as well as the associated records. So when we
1151
+ # call one of these deletion methods, what exactly should be deleted?
1152
+ #
1153
+ # The answer is that it is assumed that deletion on an association is about removing the
1154
+ # <i>link</i> between the owner and the associated object(s), rather than necessarily the
1155
+ # associated objects themselves. So with #has_and_belongs_to_many and #has_many
1156
+ # <tt>:through</tt>, the join records will be deleted, but the associated records won't.
1157
+ #
1158
+ # This makes sense if you think about it: if you were to call <tt>post.tags.delete(Tag.find_by(name: 'food'))</tt>
1159
+ # you would want the 'food' tag to be unlinked from the post, rather than for the tag itself
1160
+ # to be removed from the database.
1161
+ #
1162
+ # However, there are examples where this strategy doesn't make sense. For example, suppose
1163
+ # a person has many projects, and each project has many tasks. If we deleted one of a person's
1164
+ # tasks, we would probably not want the project to be deleted. In this scenario, the delete method
1165
+ # won't actually work: it can only be used if the association on the join model is a
1166
+ # #belongs_to. In other situations you are expected to perform operations directly on
1167
+ # either the associated records or the <tt>:through</tt> association.
1168
+ #
1169
+ # With a regular #has_many there is no distinction between the "associated records"
1170
+ # and the "link", so there is only one choice for what gets deleted.
1171
+ #
1172
+ # With #has_and_belongs_to_many and #has_many <tt>:through</tt>, if you want to delete the
1173
+ # associated records themselves, you can always do something along the lines of
1174
+ # <tt>person.tasks.each(&:destroy)</tt>.
1175
+ #
1176
+ # == Type safety with ActiveRecord::AssociationTypeMismatch
1177
+ #
1178
+ # If you attempt to assign an object to an association that doesn't match the inferred
1179
+ # or specified <tt>:class_name</tt>, you'll get an ActiveRecord::AssociationTypeMismatch.
1180
+ #
1181
+ # == Options
1182
+ #
1183
+ # All of the association macros can be specialized through options. This makes cases
1184
+ # more complex than the simple and guessable ones possible.
1185
+ module ClassMethods
1186
+ # Specifies a one-to-many association. The following methods for retrieval and query of
1187
+ # collections of associated objects will be added:
1188
+ #
1189
+ # +collection+ is a placeholder for the symbol passed as the +name+ argument, so
1190
+ # <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.
1191
+ #
1192
+ # [collection(force_reload = false)]
1193
+ # Returns a Relation of all the associated objects.
1194
+ # An empty Relation is returned if none are found.
1195
+ # [collection<<(object, ...)]
1196
+ # Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
1197
+ # Note that this operation instantly fires update SQL without waiting for the save or update call on the
1198
+ # parent object, unless the parent object is a new record.
1199
+ # This will also run validations and callbacks of associated object(s).
1200
+ # [collection.delete(object, ...)]
1201
+ # Removes one or more objects from the collection by setting their foreign keys to +NULL+.
1202
+ # Objects will be in addition destroyed if they're associated with <tt>dependent: :destroy</tt>,
1203
+ # and deleted if they're associated with <tt>dependent: :delete_all</tt>.
1204
+ #
1205
+ # If the <tt>:through</tt> option is used, then the join records are deleted (rather than
1206
+ # nullified) by default, but you can specify <tt>dependent: :destroy</tt> or
1207
+ # <tt>dependent: :nullify</tt> to override this.
1208
+ # [collection.destroy(object, ...)]
1209
+ # Removes one or more objects from the collection by running <tt>destroy</tt> on
1210
+ # each record, regardless of any dependent option, ensuring callbacks are run.
1211
+ #
1212
+ # If the <tt>:through</tt> option is used, then the join records are destroyed
1213
+ # instead, not the objects themselves.
1214
+ # [collection=objects]
1215
+ # Replaces the collections content by deleting and adding objects as appropriate. If the <tt>:through</tt>
1216
+ # option is true callbacks in the join models are triggered except destroy callbacks, since deletion is
1217
+ # direct by default. You can specify <tt>dependent: :destroy</tt> or
1218
+ # <tt>dependent: :nullify</tt> to override this.
1219
+ # [collection_singular_ids]
1220
+ # Returns an array of the associated objects' ids
1221
+ # [collection_singular_ids=ids]
1222
+ # Replace the collection with the objects identified by the primary keys in +ids+. This
1223
+ # method loads the models and calls <tt>collection=</tt>. See above.
1224
+ # [collection.clear]
1225
+ # Removes every object from the collection. This destroys the associated objects if they
1226
+ # are associated with <tt>dependent: :destroy</tt>, deletes them directly from the
1227
+ # database if <tt>dependent: :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
1228
+ # If the <tt>:through</tt> option is true no destroy callbacks are invoked on the join models.
1229
+ # Join models are directly deleted.
1230
+ # [collection.empty?]
1231
+ # Returns +true+ if there are no associated objects.
1232
+ # [collection.size]
1233
+ # Returns the number of associated objects.
1234
+ # [collection.find(...)]
1235
+ # Finds an associated object according to the same rules as ActiveRecord::FinderMethods#find.
1236
+ # [collection.exists?(...)]
1237
+ # Checks whether an associated object with the given conditions exists.
1238
+ # Uses the same rules as ActiveRecord::FinderMethods#exists?.
1239
+ # [collection.build(attributes = {}, ...)]
1240
+ # Returns one or more new objects of the collection type that have been instantiated
1241
+ # with +attributes+ and linked to this object through a foreign key, but have not yet
1242
+ # been saved.
1243
+ # [collection.create(attributes = {})]
1244
+ # Returns a new object of the collection type that has been instantiated
1245
+ # with +attributes+, linked to this object through a foreign key, and that has already
1246
+ # been saved (if it passed the validation). *Note*: This only works if the base model
1247
+ # already exists in the DB, not if it is a new (unsaved) record!
1248
+ # [collection.create!(attributes = {})]
1249
+ # Does the same as <tt>collection.create</tt>, but raises ActiveRecord::RecordInvalid
1250
+ # if the record is invalid.
1251
+ # [collection.reload]
1252
+ # Returns a Relation of all of the associated objects, forcing a database read.
1253
+ # An empty Relation is returned if none are found.
1254
+ #
1255
+ # === Example
1256
+ #
1257
+ # A <tt>Firm</tt> class declares <tt>has_many :clients</tt>, which will add:
1258
+ # * <tt>Firm#clients</tt> (similar to <tt>Client.where(firm_id: id)</tt>)
1259
+ # * <tt>Firm#clients<<</tt>
1260
+ # * <tt>Firm#clients.delete</tt>
1261
+ # * <tt>Firm#clients.destroy</tt>
1262
+ # * <tt>Firm#clients=</tt>
1263
+ # * <tt>Firm#client_ids</tt>
1264
+ # * <tt>Firm#client_ids=</tt>
1265
+ # * <tt>Firm#clients.clear</tt>
1266
+ # * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
1267
+ # * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
1268
+ # * <tt>Firm#clients.find</tt> (similar to <tt>Client.where(firm_id: id).find(id)</tt>)
1269
+ # * <tt>Firm#clients.exists?(name: 'ACME')</tt> (similar to <tt>Client.exists?(name: 'ACME', firm_id: firm.id)</tt>)
1270
+ # * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
1271
+ # * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
1272
+ # * <tt>Firm#clients.create!</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save!</tt>)
1273
+ # * <tt>Firm#clients.reload</tt>
1274
+ # The declaration can also include an +options+ hash to specialize the behavior of the association.
1275
+ #
1276
+ # === Scopes
1277
+ #
1278
+ # You can pass a second argument +scope+ as a callable (i.e. proc or
1279
+ # lambda) to retrieve a specific set of records or customize the generated
1280
+ # query when you access the associated collection.
1281
+ #
1282
+ # Scope examples:
1283
+ # has_many :comments, -> { where(author_id: 1) }
1284
+ # has_many :employees, -> { joins(:address) }
1285
+ # has_many :posts, ->(blog) { where("max_post_length > ?", blog.max_post_length) }
1286
+ #
1287
+ # === Extensions
1288
+ #
1289
+ # The +extension+ argument allows you to pass a block into a has_many
1290
+ # association. This is useful for adding new finders, creators and other
1291
+ # factory-type methods to be used as part of the association.
1292
+ #
1293
+ # Extension examples:
1294
+ # has_many :employees do
1295
+ # def find_or_create_by_name(name)
1296
+ # first_name, last_name = name.split(" ", 2)
1297
+ # find_or_create_by(first_name: first_name, last_name: last_name)
1298
+ # end
1299
+ # end
1300
+ #
1301
+ # === Options
1302
+ # [:class_name]
1303
+ # Specify the class name of the association. Use it only if that name can't be inferred
1304
+ # from the association name. So <tt>has_many :products</tt> will by default be linked
1305
+ # to the +Product+ class, but if the real class name is +SpecialProduct+, you'll have to
1306
+ # specify it with this option.
1307
+ # [:foreign_key]
1308
+ # Specify the foreign key used for the association. By default this is guessed to be the name
1309
+ # of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_many
1310
+ # association will use "person_id" as the default <tt>:foreign_key</tt>.
1311
+ # [:foreign_type]
1312
+ # Specify the column used to store the associated object's type, if this is a polymorphic
1313
+ # association. By default this is guessed to be the name of the polymorphic association
1314
+ # specified on "as" option with a "_type" suffix. So a class that defines a
1315
+ # <tt>has_many :tags, as: :taggable</tt> association will use "taggable_type" as the
1316
+ # default <tt>:foreign_type</tt>.
1317
+ # [:primary_key]
1318
+ # Specify the name of the column to use as the primary key for the association. By default this is +id+.
1319
+ # [:dependent]
1320
+ # Controls what happens to the associated objects when
1321
+ # their owner is destroyed. Note that these are implemented as
1322
+ # callbacks, and Rails executes callbacks in order. Therefore, other
1323
+ # similar callbacks may affect the <tt>:dependent</tt> behavior, and the
1324
+ # <tt>:dependent</tt> behavior may affect other callbacks.
1325
+ #
1326
+ # * <tt>:destroy</tt> causes all the associated objects to also be destroyed.
1327
+ # * <tt>:delete_all</tt> causes all the associated objects to be deleted directly from the database (so callbacks will not be executed).
1328
+ # * <tt>:nullify</tt> causes the foreign keys to be set to +NULL+. Callbacks are not executed.
1329
+ # * <tt>:restrict_with_exception</tt> causes an exception to be raised if there are any associated records.
1330
+ # * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there are any associated objects.
1331
+ #
1332
+ # If using with the <tt>:through</tt> option, the association on the join model must be
1333
+ # a #belongs_to, and the records which get deleted are the join records, rather than
1334
+ # the associated records.
1335
+ #
1336
+ # If using <tt>dependent: :destroy</tt> on a scoped association, only the scoped objects are destroyed.
1337
+ # For example, if a Post model defines
1338
+ # <tt>has_many :comments, -> { where published: true }, dependent: :destroy</tt> and <tt>destroy</tt> is
1339
+ # called on a post, only published comments are destroyed. This means that any unpublished comments in the
1340
+ # database would still contain a foreign key pointing to the now deleted post.
1341
+ # [:counter_cache]
1342
+ # This option can be used to configure a custom named <tt>:counter_cache.</tt> You only need this option,
1343
+ # when you customized the name of your <tt>:counter_cache</tt> on the #belongs_to association.
1344
+ # [:as]
1345
+ # Specifies a polymorphic interface (See #belongs_to).
1346
+ # [:through]
1347
+ # Specifies an association through which to perform the query. This can be any other type
1348
+ # of association, including other <tt>:through</tt> associations. Options for <tt>:class_name</tt>,
1349
+ # <tt>:primary_key</tt> and <tt>:foreign_key</tt> are ignored, as the association uses the
1350
+ # source reflection.
1351
+ #
1352
+ # If the association on the join model is a #belongs_to, the collection can be modified
1353
+ # and the records on the <tt>:through</tt> model will be automatically created and removed
1354
+ # as appropriate. Otherwise, the collection is read-only, so you should manipulate the
1355
+ # <tt>:through</tt> association directly.
1356
+ #
1357
+ # If you are going to modify the association (rather than just read from it), then it is
1358
+ # a good idea to set the <tt>:inverse_of</tt> option on the source association on the
1359
+ # join model. This allows associated records to be built which will automatically create
1360
+ # the appropriate join model records when they are saved. (See the 'Association Join Models'
1361
+ # section above.)
1362
+ # [:source]
1363
+ # Specifies the source association name used by #has_many <tt>:through</tt> queries.
1364
+ # Only use it if the name cannot be inferred from the association.
1365
+ # <tt>has_many :subscribers, through: :subscriptions</tt> will look for either <tt>:subscribers</tt> or
1366
+ # <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
1367
+ # [:source_type]
1368
+ # Specifies type of the source association used by #has_many <tt>:through</tt> queries where the source
1369
+ # association is a polymorphic #belongs_to.
1370
+ # [:validate]
1371
+ # When set to +true+, validates new objects added to association when saving the parent object. +true+ by default.
1372
+ # If you want to ensure associated objects are revalidated on every update, use +validates_associated+.
1373
+ # [:autosave]
1374
+ # If true, always save the associated objects or destroy them if marked for destruction,
1375
+ # when saving the parent object. If false, never save or destroy the associated objects.
1376
+ # By default, only save associated objects that are new records. This option is implemented as a
1377
+ # +before_save+ callback. Because callbacks are run in the order they are defined, associated objects
1378
+ # may need to be explicitly saved in any user-defined +before_save+ callbacks.
1379
+ #
1380
+ # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets
1381
+ # <tt>:autosave</tt> to <tt>true</tt>.
1382
+ # [:inverse_of]
1383
+ # Specifies the name of the #belongs_to association on the associated object
1384
+ # that is the inverse of this #has_many association. Does not work in combination
1385
+ # with <tt>:through</tt> or <tt>:as</tt> options.
1386
+ # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
1387
+ # [:extend]
1388
+ # Specifies a module or array of modules that will be extended into the association object returned.
1389
+ # Useful for defining methods on associations, especially when they should be shared between multiple
1390
+ # association objects.
1391
+ #
1392
+ # Option examples:
1393
+ # has_many :comments, -> { order("posted_on") }
1394
+ # has_many :comments, -> { includes(:author) }
1395
+ # has_many :people, -> { where(deleted: false).order("name") }, class_name: "Person"
1396
+ # has_many :tracks, -> { order("position") }, dependent: :destroy
1397
+ # has_many :comments, dependent: :nullify
1398
+ # has_many :tags, as: :taggable
1399
+ # has_many :reports, -> { readonly }
1400
+ # has_many :subscribers, through: :subscriptions, source: :user
1401
+ def has_many(name, scope = nil, options = {}, &extension)
1402
+ reflection = Builder::HasMany.build(self, name, scope, options, &extension)
1403
+ Reflection.add_reflection self, name, reflection
1404
+ end
1405
+
1406
+ # Specifies a one-to-one association with another class. This method should only be used
1407
+ # if the other class contains the foreign key. If the current class contains the foreign key,
1408
+ # then you should use #belongs_to instead. See also ActiveRecord::Associations::ClassMethods's overview
1409
+ # on when to use #has_one and when to use #belongs_to.
1410
+ #
1411
+ # The following methods for retrieval and query of a single associated object will be added:
1412
+ #
1413
+ # +association+ is a placeholder for the symbol passed as the +name+ argument, so
1414
+ # <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.
1415
+ #
1416
+ # [association]
1417
+ # Returns the associated object. +nil+ is returned if none is found.
1418
+ # [association=(associate)]
1419
+ # Assigns the associate object, extracts the primary key, sets it as the foreign key,
1420
+ # and saves the associate object. To avoid database inconsistencies, permanently deletes an existing
1421
+ # associated object when assigning a new one, even if the new one isn't saved to database.
1422
+ # [build_association(attributes = {})]
1423
+ # Returns a new object of the associated type that has been instantiated
1424
+ # with +attributes+ and linked to this object through a foreign key, but has not
1425
+ # yet been saved.
1426
+ # [create_association(attributes = {})]
1427
+ # Returns a new object of the associated type that has been instantiated
1428
+ # with +attributes+, linked to this object through a foreign key, and that
1429
+ # has already been saved (if it passed the validation).
1430
+ # [create_association!(attributes = {})]
1431
+ # Does the same as <tt>create_association</tt>, but raises ActiveRecord::RecordInvalid
1432
+ # if the record is invalid.
1433
+ # [reload_association]
1434
+ # Returns the associated object, forcing a database read.
1435
+ #
1436
+ # === Example
1437
+ #
1438
+ # An Account class declares <tt>has_one :beneficiary</tt>, which will add:
1439
+ # * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.where(account_id: id).first</tt>)
1440
+ # * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
1441
+ # * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
1442
+ # * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
1443
+ # * <tt>Account#create_beneficiary!</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save!; b</tt>)
1444
+ # * <tt>Account#reload_beneficiary</tt>
1445
+ #
1446
+ # === Scopes
1447
+ #
1448
+ # You can pass a second argument +scope+ as a callable (i.e. proc or
1449
+ # lambda) to retrieve a specific record or customize the generated query
1450
+ # when you access the associated object.
1451
+ #
1452
+ # Scope examples:
1453
+ # has_one :author, -> { where(comment_id: 1) }
1454
+ # has_one :employer, -> { joins(:company) }
1455
+ # has_one :latest_post, ->(blog) { where("created_at > ?", blog.enabled_at) }
1456
+ #
1457
+ # === Options
1458
+ #
1459
+ # The declaration can also include an +options+ hash to specialize the behavior of the association.
1460
+ #
1461
+ # Options are:
1462
+ # [:class_name]
1463
+ # Specify the class name of the association. Use it only if that name can't be inferred
1464
+ # from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
1465
+ # if the real class name is Person, you'll have to specify it with this option.
1466
+ # [:dependent]
1467
+ # Controls what happens to the associated object when
1468
+ # its owner is destroyed:
1469
+ #
1470
+ # * <tt>:destroy</tt> causes the associated object to also be destroyed
1471
+ # * <tt>:delete</tt> causes the associated object to be deleted directly from the database (so callbacks will not execute)
1472
+ # * <tt>:nullify</tt> causes the foreign key to be set to +NULL+. Callbacks are not executed.
1473
+ # * <tt>:restrict_with_exception</tt> causes an exception to be raised if there is an associated record
1474
+ # * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there is an associated object
1475
+ #
1476
+ # Note that <tt>:dependent</tt> option is ignored when using <tt>:through</tt> option.
1477
+ # [:foreign_key]
1478
+ # Specify the foreign key used for the association. By default this is guessed to be the name
1479
+ # of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_one association
1480
+ # will use "person_id" as the default <tt>:foreign_key</tt>.
1481
+ # [:foreign_type]
1482
+ # Specify the column used to store the associated object's type, if this is a polymorphic
1483
+ # association. By default this is guessed to be the name of the polymorphic association
1484
+ # specified on "as" option with a "_type" suffix. So a class that defines a
1485
+ # <tt>has_one :tag, as: :taggable</tt> association will use "taggable_type" as the
1486
+ # default <tt>:foreign_type</tt>.
1487
+ # [:primary_key]
1488
+ # Specify the method that returns the primary key used for the association. By default this is +id+.
1489
+ # [:as]
1490
+ # Specifies a polymorphic interface (See #belongs_to).
1491
+ # [:through]
1492
+ # Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>,
1493
+ # <tt>:primary_key</tt>, and <tt>:foreign_key</tt> are ignored, as the association uses the
1494
+ # source reflection. You can only use a <tt>:through</tt> query through a #has_one
1495
+ # or #belongs_to association on the join model.
1496
+ # [:source]
1497
+ # Specifies the source association name used by #has_one <tt>:through</tt> queries.
1498
+ # Only use it if the name cannot be inferred from the association.
1499
+ # <tt>has_one :favorite, through: :favorites</tt> will look for a
1500
+ # <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
1501
+ # [:source_type]
1502
+ # Specifies type of the source association used by #has_one <tt>:through</tt> queries where the source
1503
+ # association is a polymorphic #belongs_to.
1504
+ # [:validate]
1505
+ # When set to +true+, validates new objects added to association when saving the parent object. +false+ by default.
1506
+ # If you want to ensure associated objects are revalidated on every update, use +validates_associated+.
1507
+ # [:autosave]
1508
+ # If true, always save the associated object or destroy it if marked for destruction,
1509
+ # when saving the parent object. If false, never save or destroy the associated object.
1510
+ # By default, only save the associated object if it's a new record.
1511
+ #
1512
+ # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets
1513
+ # <tt>:autosave</tt> to <tt>true</tt>.
1514
+ # [:inverse_of]
1515
+ # Specifies the name of the #belongs_to association on the associated object
1516
+ # that is the inverse of this #has_one association. Does not work in combination
1517
+ # with <tt>:through</tt> or <tt>:as</tt> options.
1518
+ # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
1519
+ # [:required]
1520
+ # When set to +true+, the association will also have its presence validated.
1521
+ # This will validate the association itself, not the id. You can use
1522
+ # +:inverse_of+ to avoid an extra query during validation.
1523
+ #
1524
+ # Option examples:
1525
+ # has_one :credit_card, dependent: :destroy # destroys the associated credit card
1526
+ # has_one :credit_card, dependent: :nullify # updates the associated records foreign
1527
+ # # key value to NULL rather than destroying it
1528
+ # has_one :last_comment, -> { order('posted_on') }, class_name: "Comment"
1529
+ # has_one :project_manager, -> { where(role: 'project_manager') }, class_name: "Person"
1530
+ # has_one :attachment, as: :attachable
1531
+ # has_one :boss, -> { readonly }
1532
+ # has_one :club, through: :membership
1533
+ # has_one :primary_address, -> { where(primary: true) }, through: :addressables, source: :addressable
1534
+ # has_one :credit_card, required: true
1535
+ def has_one(name, scope = nil, options = {})
1536
+ reflection = Builder::HasOne.build(self, name, scope, options)
1537
+ Reflection.add_reflection self, name, reflection
1814
1538
  end
1815
1539
 
1816
- habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(name, scope, options, self)
1540
+ # Specifies a one-to-one association with another class. This method should only be used
1541
+ # if this class contains the foreign key. If the other class contains the foreign key,
1542
+ # then you should use #has_one instead. See also ActiveRecord::Associations::ClassMethods's overview
1543
+ # on when to use #has_one and when to use #belongs_to.
1544
+ #
1545
+ # Methods will be added for retrieval and query for a single associated object, for which
1546
+ # this object holds an id:
1547
+ #
1548
+ # +association+ is a placeholder for the symbol passed as the +name+ argument, so
1549
+ # <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.
1550
+ #
1551
+ # [association]
1552
+ # Returns the associated object. +nil+ is returned if none is found.
1553
+ # [association=(associate)]
1554
+ # Assigns the associate object, extracts the primary key, and sets it as the foreign key.
1555
+ # [build_association(attributes = {})]
1556
+ # Returns a new object of the associated type that has been instantiated
1557
+ # with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
1558
+ # [create_association(attributes = {})]
1559
+ # Returns a new object of the associated type that has been instantiated
1560
+ # with +attributes+, linked to this object through a foreign key, and that
1561
+ # has already been saved (if it passed the validation).
1562
+ # [create_association!(attributes = {})]
1563
+ # Does the same as <tt>create_association</tt>, but raises ActiveRecord::RecordInvalid
1564
+ # if the record is invalid.
1565
+ # [reload_association]
1566
+ # Returns the associated object, forcing a database read.
1567
+ #
1568
+ # === Example
1569
+ #
1570
+ # A Post class declares <tt>belongs_to :author</tt>, which will add:
1571
+ # * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
1572
+ # * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
1573
+ # * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
1574
+ # * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
1575
+ # * <tt>Post#create_author!</tt> (similar to <tt>post.author = Author.new; post.author.save!; post.author</tt>)
1576
+ # * <tt>Post#reload_author</tt>
1577
+ # The declaration can also include an +options+ hash to specialize the behavior of the association.
1578
+ #
1579
+ # === Scopes
1580
+ #
1581
+ # You can pass a second argument +scope+ as a callable (i.e. proc or
1582
+ # lambda) to retrieve a specific record or customize the generated query
1583
+ # when you access the associated object.
1584
+ #
1585
+ # Scope examples:
1586
+ # belongs_to :firm, -> { where(id: 2) }
1587
+ # belongs_to :user, -> { joins(:friends) }
1588
+ # belongs_to :level, ->(game) { where("game_level > ?", game.current_level) }
1589
+ #
1590
+ # === Options
1591
+ #
1592
+ # [:class_name]
1593
+ # Specify the class name of the association. Use it only if that name can't be inferred
1594
+ # from the association name. So <tt>belongs_to :author</tt> will by default be linked to the Author class, but
1595
+ # if the real class name is Person, you'll have to specify it with this option.
1596
+ # [:foreign_key]
1597
+ # Specify the foreign key used for the association. By default this is guessed to be the name
1598
+ # of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
1599
+ # association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly,
1600
+ # <tt>belongs_to :favorite_person, class_name: "Person"</tt> will use a foreign key
1601
+ # of "favorite_person_id".
1602
+ # [:foreign_type]
1603
+ # Specify the column used to store the associated object's type, if this is a polymorphic
1604
+ # association. By default this is guessed to be the name of the association with a "_type"
1605
+ # suffix. So a class that defines a <tt>belongs_to :taggable, polymorphic: true</tt>
1606
+ # association will use "taggable_type" as the default <tt>:foreign_type</tt>.
1607
+ # [:primary_key]
1608
+ # Specify the method that returns the primary key of associated object used for the association.
1609
+ # By default this is id.
1610
+ # [:dependent]
1611
+ # If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
1612
+ # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
1613
+ # This option should not be specified when #belongs_to is used in conjunction with
1614
+ # a #has_many relationship on another class because of the potential to leave
1615
+ # orphaned records behind.
1616
+ # [:counter_cache]
1617
+ # Caches the number of belonging objects on the associate class through the use of CounterCache::ClassMethods#increment_counter
1618
+ # and CounterCache::ClassMethods#decrement_counter. The counter cache is incremented when an object of this
1619
+ # class is created and decremented when it's destroyed. This requires that a column
1620
+ # named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
1621
+ # is used on the associate class (such as a Post class) - that is the migration for
1622
+ # <tt>#{table_name}_count</tt> is created on the associate class (such that <tt>Post.comments_count</tt> will
1623
+ # return the count cached, see note below). You can also specify a custom counter
1624
+ # cache column by providing a column name instead of a +true+/+false+ value to this
1625
+ # option (e.g., <tt>counter_cache: :my_custom_counter</tt>.)
1626
+ # Note: Specifying a counter cache will add it to that model's list of readonly attributes
1627
+ # using +attr_readonly+.
1628
+ # [:polymorphic]
1629
+ # Specify this association is a polymorphic association by passing +true+.
1630
+ # Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
1631
+ # to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
1632
+ # [:validate]
1633
+ # When set to +true+, validates new objects added to association when saving the parent object. +false+ by default.
1634
+ # If you want to ensure associated objects are revalidated on every update, use +validates_associated+.
1635
+ # [:autosave]
1636
+ # If true, always save the associated object or destroy it if marked for destruction, when
1637
+ # saving the parent object.
1638
+ # If false, never save or destroy the associated object.
1639
+ # By default, only save the associated object if it's a new record.
1640
+ #
1641
+ # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for
1642
+ # sets <tt>:autosave</tt> to <tt>true</tt>.
1643
+ # [:touch]
1644
+ # If true, the associated object will be touched (the updated_at/on attributes set to current time)
1645
+ # when this record is either saved or destroyed. If you specify a symbol, that attribute
1646
+ # will be updated with the current time in addition to the updated_at/on attribute.
1647
+ # Please note that with touching no validation is performed and only the +after_touch+,
1648
+ # +after_commit+ and +after_rollback+ callbacks are executed.
1649
+ # [:inverse_of]
1650
+ # Specifies the name of the #has_one or #has_many association on the associated
1651
+ # object that is the inverse of this #belongs_to association. Does not work in
1652
+ # combination with the <tt>:polymorphic</tt> options.
1653
+ # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
1654
+ # [:optional]
1655
+ # When set to +true+, the association will not have its presence validated.
1656
+ # [:required]
1657
+ # When set to +true+, the association will also have its presence validated.
1658
+ # This will validate the association itself, not the id. You can use
1659
+ # +:inverse_of+ to avoid an extra query during validation.
1660
+ # NOTE: <tt>required</tt> is set to <tt>true</tt> by default and is deprecated. If
1661
+ # you don't want to have association presence validated, use <tt>optional: true</tt>.
1662
+ # [:default]
1663
+ # Provide a callable (i.e. proc or lambda) to specify that the association should
1664
+ # be initialized with a particular record before validation.
1665
+ #
1666
+ # Option examples:
1667
+ # belongs_to :firm, foreign_key: "client_of"
1668
+ # belongs_to :person, primary_key: "name", foreign_key: "person_name"
1669
+ # belongs_to :author, class_name: "Person", foreign_key: "author_id"
1670
+ # belongs_to :valid_coupon, ->(o) { where "discounts > ?", o.payments_count },
1671
+ # class_name: "Coupon", foreign_key: "coupon_id"
1672
+ # belongs_to :attachable, polymorphic: true
1673
+ # belongs_to :project, -> { readonly }
1674
+ # belongs_to :post, counter_cache: true
1675
+ # belongs_to :comment, touch: true
1676
+ # belongs_to :company, touch: :employees_last_updated_at
1677
+ # belongs_to :user, optional: true
1678
+ # belongs_to :account, default: -> { company.account }
1679
+ def belongs_to(name, scope = nil, options = {})
1680
+ reflection = Builder::BelongsTo.build(self, name, scope, options)
1681
+ Reflection.add_reflection self, name, reflection
1682
+ end
1817
1683
 
1818
- builder = Builder::HasAndBelongsToMany.new name, self, options
1684
+ # Specifies a many-to-many relationship with another class. This associates two classes via an
1685
+ # intermediate join table. Unless the join table is explicitly specified as an option, it is
1686
+ # guessed using the lexical order of the class names. So a join between Developer and Project
1687
+ # will give the default join table name of "developers_projects" because "D" precedes "P" alphabetically.
1688
+ # Note that this precedence is calculated using the <tt><</tt> operator for String. This
1689
+ # means that if the strings are of different lengths, and the strings are equal when compared
1690
+ # up to the shortest length, then the longer string is considered of higher
1691
+ # lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers"
1692
+ # to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes",
1693
+ # but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the
1694
+ # custom <tt>:join_table</tt> option if you need to.
1695
+ # If your tables share a common prefix, it will only appear once at the beginning. For example,
1696
+ # the tables "catalog_categories" and "catalog_products" generate a join table name of "catalog_categories_products".
1697
+ #
1698
+ # The join table should not have a primary key or a model associated with it. You must manually generate the
1699
+ # join table with a migration such as this:
1700
+ #
1701
+ # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration[5.0]
1702
+ # def change
1703
+ # create_join_table :developers, :projects
1704
+ # end
1705
+ # end
1706
+ #
1707
+ # It's also a good idea to add indexes to each of those columns to speed up the joins process.
1708
+ # However, in MySQL it is advised to add a compound index for both of the columns as MySQL only
1709
+ # uses one index per table during the lookup.
1710
+ #
1711
+ # Adds the following methods for retrieval and query:
1712
+ #
1713
+ # +collection+ is a placeholder for the symbol passed as the +name+ argument, so
1714
+ # <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.
1715
+ #
1716
+ # [collection]
1717
+ # Returns a Relation of all the associated objects.
1718
+ # An empty Relation is returned if none are found.
1719
+ # [collection<<(object, ...)]
1720
+ # Adds one or more objects to the collection by creating associations in the join table
1721
+ # (<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to this method).
1722
+ # Note that this operation instantly fires update SQL without waiting for the save or update call on the
1723
+ # parent object, unless the parent object is a new record.
1724
+ # [collection.delete(object, ...)]
1725
+ # Removes one or more objects from the collection by removing their associations from the join table.
1726
+ # This does not destroy the objects.
1727
+ # [collection.destroy(object, ...)]
1728
+ # Removes one or more objects from the collection by running destroy on each association in the join table, overriding any dependent option.
1729
+ # This does not destroy the objects.
1730
+ # [collection=objects]
1731
+ # Replaces the collection's content by deleting and adding objects as appropriate.
1732
+ # [collection_singular_ids]
1733
+ # Returns an array of the associated objects' ids.
1734
+ # [collection_singular_ids=ids]
1735
+ # Replace the collection by the objects identified by the primary keys in +ids+.
1736
+ # [collection.clear]
1737
+ # Removes every object from the collection. This does not destroy the objects.
1738
+ # [collection.empty?]
1739
+ # Returns +true+ if there are no associated objects.
1740
+ # [collection.size]
1741
+ # Returns the number of associated objects.
1742
+ # [collection.find(id)]
1743
+ # Finds an associated object responding to the +id+ and that
1744
+ # meets the condition that it has to be associated with this object.
1745
+ # Uses the same rules as ActiveRecord::FinderMethods#find.
1746
+ # [collection.exists?(...)]
1747
+ # Checks whether an associated object with the given conditions exists.
1748
+ # Uses the same rules as ActiveRecord::FinderMethods#exists?.
1749
+ # [collection.build(attributes = {})]
1750
+ # Returns a new object of the collection type that has been instantiated
1751
+ # with +attributes+ and linked to this object through the join table, but has not yet been saved.
1752
+ # [collection.create(attributes = {})]
1753
+ # Returns a new object of the collection type that has been instantiated
1754
+ # with +attributes+, linked to this object through the join table, and that has already been
1755
+ # saved (if it passed the validation).
1756
+ # [collection.reload]
1757
+ # Returns a Relation of all of the associated objects, forcing a database read.
1758
+ # An empty Relation is returned if none are found.
1759
+ #
1760
+ # === Example
1761
+ #
1762
+ # A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
1763
+ # * <tt>Developer#projects</tt>
1764
+ # * <tt>Developer#projects<<</tt>
1765
+ # * <tt>Developer#projects.delete</tt>
1766
+ # * <tt>Developer#projects.destroy</tt>
1767
+ # * <tt>Developer#projects=</tt>
1768
+ # * <tt>Developer#project_ids</tt>
1769
+ # * <tt>Developer#project_ids=</tt>
1770
+ # * <tt>Developer#projects.clear</tt>
1771
+ # * <tt>Developer#projects.empty?</tt>
1772
+ # * <tt>Developer#projects.size</tt>
1773
+ # * <tt>Developer#projects.find(id)</tt>
1774
+ # * <tt>Developer#projects.exists?(...)</tt>
1775
+ # * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("developer_id" => id)</tt>)
1776
+ # * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("developer_id" => id); c.save; c</tt>)
1777
+ # * <tt>Developer#projects.reload</tt>
1778
+ # The declaration may include an +options+ hash to specialize the behavior of the association.
1779
+ #
1780
+ # === Scopes
1781
+ #
1782
+ # You can pass a second argument +scope+ as a callable (i.e. proc or
1783
+ # lambda) to retrieve a specific set of records or customize the generated
1784
+ # query when you access the associated collection.
1785
+ #
1786
+ # Scope examples:
1787
+ # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) }
1788
+ # has_and_belongs_to_many :categories, ->(post) {
1789
+ # where("default_category = ?", post.default_category)
1790
+ #
1791
+ # === Extensions
1792
+ #
1793
+ # The +extension+ argument allows you to pass a block into a
1794
+ # has_and_belongs_to_many association. This is useful for adding new
1795
+ # finders, creators and other factory-type methods to be used as part of
1796
+ # the association.
1797
+ #
1798
+ # Extension examples:
1799
+ # has_and_belongs_to_many :contractors do
1800
+ # def find_or_create_by_name(name)
1801
+ # first_name, last_name = name.split(" ", 2)
1802
+ # find_or_create_by(first_name: first_name, last_name: last_name)
1803
+ # end
1804
+ # end
1805
+ #
1806
+ # === Options
1807
+ #
1808
+ # [:class_name]
1809
+ # Specify the class name of the association. Use it only if that name can't be inferred
1810
+ # from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
1811
+ # Project class, but if the real class name is SuperProject, you'll have to specify it with this option.
1812
+ # [:join_table]
1813
+ # Specify the name of the join table if the default based on lexical order isn't what you want.
1814
+ # <b>WARNING:</b> If you're overwriting the table name of either class, the +table_name+ method
1815
+ # MUST be declared underneath any #has_and_belongs_to_many declaration in order to work.
1816
+ # [:foreign_key]
1817
+ # Specify the foreign key used for the association. By default this is guessed to be the name
1818
+ # of this class in lower-case and "_id" suffixed. So a Person class that makes
1819
+ # a #has_and_belongs_to_many association to Project will use "person_id" as the
1820
+ # default <tt>:foreign_key</tt>.
1821
+ # [:association_foreign_key]
1822
+ # Specify the foreign key used for the association on the receiving side of the association.
1823
+ # By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
1824
+ # So if a Person class makes a #has_and_belongs_to_many association to Project,
1825
+ # the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
1826
+ # [:validate]
1827
+ # When set to +true+, validates new objects added to association when saving the parent object. +true+ by default.
1828
+ # If you want to ensure associated objects are revalidated on every update, use +validates_associated+.
1829
+ # [:autosave]
1830
+ # If true, always save the associated objects or destroy them if marked for destruction, when
1831
+ # saving the parent object.
1832
+ # If false, never save or destroy the associated objects.
1833
+ # By default, only save associated objects that are new records.
1834
+ #
1835
+ # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets
1836
+ # <tt>:autosave</tt> to <tt>true</tt>.
1837
+ #
1838
+ # Option examples:
1839
+ # has_and_belongs_to_many :projects
1840
+ # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) }
1841
+ # has_and_belongs_to_many :nations, class_name: "Country"
1842
+ # has_and_belongs_to_many :categories, join_table: "prods_cats"
1843
+ # has_and_belongs_to_many :categories, -> { readonly }
1844
+ def has_and_belongs_to_many(name, scope = nil, **options, &extension)
1845
+ habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(name, scope, options, self)
1819
1846
 
1820
- join_model = builder.through_model
1847
+ builder = Builder::HasAndBelongsToMany.new name, self, options
1821
1848
 
1822
- const_set join_model.name, join_model
1823
- private_constant join_model.name
1849
+ join_model = ActiveSupport::Deprecation.silence { builder.through_model }
1824
1850
 
1825
- middle_reflection = builder.middle_reflection join_model
1851
+ const_set join_model.name, join_model
1852
+ private_constant join_model.name
1826
1853
 
1827
- Builder::HasMany.define_callbacks self, middle_reflection
1828
- Reflection.add_reflection self, middle_reflection.name, middle_reflection
1829
- middle_reflection.parent_reflection = habtm_reflection
1854
+ middle_reflection = builder.middle_reflection join_model
1830
1855
 
1831
- include Module.new {
1832
- class_eval <<-RUBY, __FILE__, __LINE__ + 1
1833
- def destroy_associations
1834
- association(:#{middle_reflection.name}).delete_all(:delete_all)
1835
- association(:#{name}).reset
1836
- super
1837
- end
1838
- RUBY
1839
- }
1856
+ Builder::HasMany.define_callbacks self, middle_reflection
1857
+ Reflection.add_reflection self, middle_reflection.name, middle_reflection
1858
+ middle_reflection.parent_reflection = habtm_reflection
1840
1859
 
1841
- hm_options = {}
1842
- hm_options[:through] = middle_reflection.name
1843
- hm_options[:source] = join_model.right_reflection.name
1860
+ include Module.new {
1861
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
1862
+ def destroy_associations
1863
+ association(:#{middle_reflection.name}).delete_all(:delete_all)
1864
+ association(:#{name}).reset
1865
+ super
1866
+ end
1867
+ RUBY
1868
+ }
1844
1869
 
1845
- [:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate, :join_table, :class_name, :extend].each do |k|
1846
- hm_options[k] = options[k] if options.key? k
1847
- end
1870
+ hm_options = {}
1871
+ hm_options[:through] = middle_reflection.name
1872
+ hm_options[:source] = join_model.right_reflection.name
1848
1873
 
1849
- has_many name, scope, hm_options, &extension
1850
- self._reflections[name.to_s].parent_reflection = habtm_reflection
1874
+ [:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate, :join_table, :class_name, :extend].each do |k|
1875
+ hm_options[k] = options[k] if options.key? k
1876
+ end
1877
+
1878
+ ActiveSupport::Deprecation.silence { has_many name, scope, hm_options, &extension }
1879
+ _reflections[name.to_s].parent_reflection = habtm_reflection
1880
+ end
1851
1881
  end
1852
- end
1853
1882
  end
1854
1883
  end