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