activerecord 4.2.0

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