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