radiant 0.8.0 → 0.8.1

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

Potentially problematic release.


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

Files changed (513) hide show
  1. data/CHANGELOG +33 -1
  2. data/CONTRIBUTORS +15 -2
  3. data/INSTALL +9 -7
  4. data/README +11 -7
  5. data/app/controllers/admin/layouts_controller.rb +5 -2
  6. data/app/controllers/admin/pages_controller.rb +8 -5
  7. data/app/controllers/admin/snippets_controller.rb +5 -2
  8. data/app/controllers/application_controller.rb +7 -0
  9. data/app/helpers/admin/node_helper.rb +2 -2
  10. data/app/helpers/application_helper.rb +2 -2
  11. data/app/models/radiant/config.rb +36 -4
  12. data/app/models/standard_tags.rb +1 -1
  13. data/app/views/admin/layouts/index.html.haml +15 -12
  14. data/app/views/admin/page_parts/_page_part.html.haml +2 -2
  15. data/app/views/admin/pages/index.html.haml +1 -1
  16. data/app/views/admin/snippets/_form.html.haml +1 -1
  17. data/app/views/admin/snippets/index.html.haml +14 -10
  18. data/config/database.db2.yml +20 -0
  19. data/config/environment.rb +4 -4
  20. data/config/environments/test.rb +1 -2
  21. data/features/support/env.rb +2 -1
  22. data/lib/generators/extension/extension_generator.rb +5 -0
  23. data/lib/generators/extension/templates/RSpecRakefile +11 -8
  24. data/lib/generators/extension/templates/cucumber.yml +1 -0
  25. data/lib/generators/extension/templates/cucumber_env.rb +16 -0
  26. data/lib/generators/extension/templates/cucumber_paths.rb +14 -0
  27. data/lib/generators/extension/templates/extension.rb +1 -1
  28. data/lib/generators/instance/instance_generator.rb +1 -1
  29. data/lib/generators/instance/templates/databases/db2.yml +40 -0
  30. data/lib/generators/instance/templates/instance_environment.rb +6 -6
  31. data/lib/local_time.rb +3 -9
  32. data/lib/radiant.rb +1 -1
  33. data/lib/radiant/cache.rb +10 -8
  34. data/lib/radiant/extension.rb +36 -0
  35. data/lib/radiant/extension/script.rb +1 -1
  36. data/lib/radiant/extension_loader.rb +5 -1
  37. data/lib/radiant/initializer.rb +52 -4
  38. data/lib/task_support.rb +33 -0
  39. data/lib/tasks/cucumber.rake +5 -1
  40. data/lib/tasks/radiant_config.rake +18 -0
  41. data/lib/tasks/release.rake +1 -0
  42. data/public/javascripts/admin/admin.js +1 -1
  43. data/spec/controllers/admin/layouts_controller_spec.rb +18 -12
  44. data/spec/controllers/admin/pages_controller_spec.rb +35 -29
  45. data/spec/controllers/admin/snippets_controller_spec.rb +11 -5
  46. data/spec/controllers/admin/welcome_controller_spec.rb +1 -1
  47. data/spec/controllers/application_controller_spec.rb +18 -0
  48. data/spec/fixtures/radiant_config.yml +10 -0
  49. data/spec/generators/extension_generator_spec.rb +12 -0
  50. data/spec/helpers/admin/node_helper_spec.rb +6 -0
  51. data/spec/helpers/application_helper_spec.rb +1 -1
  52. data/spec/lib/radiant/extension_loader_spec.rb +17 -0
  53. data/spec/lib/radiant/extension_spec.rb +28 -0
  54. data/spec/lib/radiant/initializer_spec.rb +34 -0
  55. data/spec/lib/task_support_spec.rb +42 -0
  56. data/spec/models/page_spec.rb +6 -2
  57. data/spec/models/radiant/config_spec.rb +42 -1
  58. data/spec/models/standard_tags_spec.rb +2 -2
  59. data/test/fixtures/extensions/01_basic/app/metal/basic_metal.rb +9 -0
  60. data/test/fixtures/extensions/02_overriding/app/metal/basic_metal.rb +9 -0
  61. data/vendor/extensions/textile_filter/textile.html +2 -2
  62. data/vendor/plugins/dataset/CHANGELOG +2 -1
  63. data/vendor/plugins/dataset/Rakefile +3 -0
  64. data/vendor/plugins/dataset/VERSION.yml +2 -2
  65. data/vendor/plugins/dataset/dataset.gemspec +9 -3
  66. data/vendor/plugins/dataset/lib/dataset.rb +3 -0
  67. data/vendor/radius/lib/radius.rb +5 -0
  68. data/vendor/radius/test/radius_test.rb +6 -0
  69. data/vendor/rails/actionmailer/CHANGELOG +8 -0
  70. data/vendor/rails/actionmailer/Rakefile +3 -2
  71. data/vendor/rails/actionmailer/lib/action_mailer/base.rb +2 -1
  72. data/vendor/rails/actionmailer/lib/action_mailer/version.rb +1 -1
  73. data/vendor/rails/actionmailer/test/abstract_unit.rb +0 -3
  74. data/vendor/rails/actionmailer/test/mail_service_test.rb +3 -2
  75. data/vendor/rails/actionpack/CHANGELOG +16 -0
  76. data/vendor/rails/actionpack/Rakefile +5 -3
  77. data/vendor/rails/actionpack/lib/action_controller.rb +2 -7
  78. data/vendor/rails/actionpack/lib/action_controller/assertions/response_assertions.rb +13 -3
  79. data/vendor/rails/actionpack/lib/action_controller/base.rb +12 -3
  80. data/vendor/rails/actionpack/lib/action_controller/caching.rb +1 -1
  81. data/vendor/rails/actionpack/lib/action_controller/caching/actions.rb +9 -1
  82. data/vendor/rails/actionpack/lib/action_controller/caching/sweeper.rb +45 -0
  83. data/vendor/rails/actionpack/lib/action_controller/caching/sweeping.rb +0 -42
  84. data/vendor/rails/actionpack/lib/action_controller/cookies.rb +1 -1
  85. data/vendor/rails/actionpack/lib/action_controller/dispatcher.rb +21 -6
  86. data/vendor/rails/actionpack/lib/action_controller/failsafe.rb +40 -6
  87. data/vendor/rails/actionpack/lib/action_controller/flash.rb +11 -3
  88. data/vendor/rails/actionpack/lib/action_controller/http_authentication.rb +7 -3
  89. data/vendor/rails/actionpack/lib/action_controller/integration.rb +5 -12
  90. data/vendor/rails/actionpack/lib/action_controller/middlewares.rb +0 -1
  91. data/vendor/rails/actionpack/lib/action_controller/params_parser.rb +6 -0
  92. data/vendor/rails/actionpack/lib/action_controller/reloader.rb +47 -7
  93. data/vendor/rails/actionpack/lib/action_controller/request.rb +6 -2
  94. data/vendor/rails/actionpack/lib/action_controller/request_forgery_protection.rb +2 -1
  95. data/vendor/rails/actionpack/lib/action_controller/resources.rb +17 -13
  96. data/vendor/rails/actionpack/lib/action_controller/response.rb +8 -2
  97. data/vendor/rails/actionpack/lib/action_controller/routing.rb +3 -0
  98. data/vendor/rails/actionpack/lib/action_controller/routing/route_set.rb +20 -6
  99. data/vendor/rails/actionpack/lib/action_controller/streaming.rb +4 -2
  100. data/vendor/rails/actionpack/lib/action_controller/test_process.rb +9 -1
  101. data/vendor/rails/actionpack/lib/action_controller/url_rewriter.rb +1 -1
  102. data/vendor/rails/actionpack/lib/action_pack/version.rb +1 -1
  103. data/vendor/rails/actionpack/lib/action_view/helpers.rb +1 -1
  104. data/vendor/rails/actionpack/lib/action_view/helpers/asset_tag_helper.rb +21 -9
  105. data/vendor/rails/actionpack/lib/action_view/helpers/atom_feed_helper.rb +1 -1
  106. data/vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb +2 -2
  107. data/vendor/rails/actionpack/lib/action_view/helpers/form_helper.rb +26 -12
  108. data/vendor/rails/actionpack/lib/action_view/helpers/form_options_helper.rb +71 -1
  109. data/vendor/rails/actionpack/lib/action_view/helpers/form_tag_helper.rb +10 -4
  110. data/vendor/rails/actionpack/lib/action_view/helpers/number_helper.rb +1 -1
  111. data/vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb +7 -7
  112. data/vendor/rails/actionpack/lib/action_view/helpers/scriptaculous_helper.rb +5 -5
  113. data/vendor/rails/actionpack/lib/action_view/helpers/tag_helper.rb +1 -1
  114. data/vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb +23 -14
  115. data/vendor/rails/actionpack/lib/action_view/helpers/url_helper.rb +2 -2
  116. data/vendor/rails/actionpack/lib/action_view/locale/en.yml +4 -0
  117. data/vendor/rails/actionpack/lib/action_view/paths.rb +1 -1
  118. data/vendor/rails/actionpack/lib/action_view/template.rb +22 -33
  119. data/vendor/rails/actionpack/test/abstract_unit.rb +17 -1
  120. data/vendor/rails/actionpack/test/activerecord/active_record_store_test.rb +3 -3
  121. data/vendor/rails/actionpack/test/controller/action_pack_assertions_test.rb +27 -0
  122. data/vendor/rails/actionpack/test/controller/caching_test.rb +40 -1
  123. data/vendor/rails/actionpack/test/controller/cookie_test.rb +16 -0
  124. data/vendor/rails/actionpack/test/controller/dispatcher_test.rb +59 -18
  125. data/vendor/rails/actionpack/test/controller/failsafe_test.rb +60 -0
  126. data/vendor/rails/actionpack/test/controller/filter_params_test.rb +3 -1
  127. data/vendor/rails/actionpack/test/controller/flash_test.rb +6 -1
  128. data/vendor/rails/actionpack/test/controller/http_basic_authentication_test.rb +25 -0
  129. data/vendor/rails/actionpack/test/controller/http_digest_authentication_test.rb +63 -9
  130. data/vendor/rails/actionpack/test/controller/integration_test.rb +31 -3
  131. data/vendor/rails/actionpack/test/controller/rack_test.rb +18 -1
  132. data/vendor/rails/actionpack/test/controller/redirect_test.rb +4 -1
  133. data/vendor/rails/actionpack/test/controller/reloader_test.rb +124 -0
  134. data/vendor/rails/actionpack/test/controller/render_test.rb +19 -9
  135. data/vendor/rails/actionpack/test/controller/request/json_params_parsing_test.rb +24 -4
  136. data/vendor/rails/actionpack/test/controller/request/multipart_params_parsing_test.rb +1 -62
  137. data/vendor/rails/actionpack/test/controller/request/test_request_test.rb +35 -0
  138. data/vendor/rails/actionpack/test/controller/request/url_encoded_params_parsing_test.rb +0 -38
  139. data/vendor/rails/actionpack/test/controller/request/xml_params_parsing_test.rb +15 -0
  140. data/vendor/rails/actionpack/test/controller/request_forgery_protection_test.rb +6 -5
  141. data/vendor/rails/actionpack/test/controller/request_test.rb +218 -230
  142. data/vendor/rails/actionpack/test/controller/resources_test.rb +52 -0
  143. data/vendor/rails/actionpack/test/controller/routing_test.rb +28 -2
  144. data/vendor/rails/actionpack/test/controller/send_file_test.rb +12 -2
  145. data/vendor/rails/actionpack/test/controller/session/cookie_store_test.rb +9 -32
  146. data/vendor/rails/actionpack/test/controller/test_test.rb +8 -0
  147. data/vendor/rails/actionpack/test/controller/url_rewriter_test.rb +29 -3
  148. data/vendor/rails/actionpack/test/fixtures/failsafe/500.html +1 -0
  149. data/vendor/rails/actionpack/test/fixtures/public/absolute/test.css +23 -0
  150. data/vendor/rails/actionpack/test/fixtures/public/absolute/test.js +63 -0
  151. data/vendor/rails/actionpack/test/template/active_record_helper_test.rb +1 -1
  152. data/vendor/rails/actionpack/test/template/asset_tag_helper_test.rb +46 -0
  153. data/vendor/rails/actionpack/test/template/atom_feed_helper_test.rb +29 -0
  154. data/vendor/rails/actionpack/test/template/form_helper_test.rb +143 -6
  155. data/vendor/rails/actionpack/test/template/form_options_helper_i18n_test.rb +27 -0
  156. data/vendor/rails/actionpack/test/template/form_options_helper_test.rb +56 -0
  157. data/vendor/rails/actionpack/test/template/form_tag_helper_test.rb +23 -6
  158. data/vendor/rails/actionpack/test/template/prototype_helper_test.rb +11 -11
  159. data/vendor/rails/actionpack/test/template/template_test.rb +32 -0
  160. data/vendor/rails/actionpack/test/template/text_helper_test.rb +23 -0
  161. data/vendor/rails/actionpack/test/template/url_helper_test.rb +8 -0
  162. data/vendor/rails/activerecord/CHANGELOG +18 -0
  163. data/vendor/rails/activerecord/Rakefile +26 -9
  164. data/vendor/rails/activerecord/examples/performance.rb +162 -0
  165. data/vendor/rails/activerecord/lib/active_record/associations.rb +104 -35
  166. data/vendor/rails/activerecord/lib/active_record/associations/association_collection.rb +10 -5
  167. data/vendor/rails/activerecord/lib/active_record/associations/association_proxy.rb +2 -2
  168. data/vendor/rails/activerecord/lib/active_record/associations/belongs_to_association.rb +22 -4
  169. data/vendor/rails/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb +5 -1
  170. data/vendor/rails/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +16 -0
  171. data/vendor/rails/activerecord/lib/active_record/associations/has_many_association.rb +1 -0
  172. data/vendor/rails/activerecord/lib/active_record/associations/has_many_through_association.rb +13 -3
  173. data/vendor/rails/activerecord/lib/active_record/associations/has_one_through_association.rb +15 -9
  174. data/vendor/rails/activerecord/lib/active_record/autosave_association.rb +15 -9
  175. data/vendor/rails/activerecord/lib/active_record/base.rb +34 -31
  176. data/vendor/rails/activerecord/lib/active_record/batches.rb +23 -15
  177. data/vendor/rails/activerecord/lib/active_record/calculations.rb +7 -13
  178. data/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +16 -2
  179. data/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +2 -2
  180. data/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +7 -0
  181. data/vendor/rails/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +17 -8
  182. data/vendor/rails/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +98 -35
  183. data/vendor/rails/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb +15 -0
  184. data/vendor/rails/activerecord/lib/active_record/dirty.rb +1 -1
  185. data/vendor/rails/activerecord/lib/active_record/fixtures.rb +14 -11
  186. data/vendor/rails/activerecord/lib/active_record/i18n_interpolation_deprecation.rb +1 -1
  187. data/vendor/rails/activerecord/lib/active_record/locale/en.yml +4 -0
  188. data/vendor/rails/activerecord/lib/active_record/named_scope.rb +3 -8
  189. data/vendor/rails/activerecord/lib/active_record/reflection.rb +1 -1
  190. data/vendor/rails/activerecord/lib/active_record/schema_dumper.rb +6 -3
  191. data/vendor/rails/activerecord/lib/active_record/serialization.rb +3 -2
  192. data/vendor/rails/activerecord/lib/active_record/serializers/json_serializer.rb +10 -18
  193. data/vendor/rails/activerecord/lib/active_record/serializers/xml_serializer.rb +6 -2
  194. data/vendor/rails/activerecord/lib/active_record/session_store.rb +9 -1
  195. data/vendor/rails/activerecord/lib/active_record/timestamp.rb +39 -9
  196. data/vendor/rails/activerecord/lib/active_record/validations.rb +149 -80
  197. data/vendor/rails/activerecord/lib/active_record/version.rb +1 -1
  198. data/vendor/rails/activerecord/test/cases/adapter_test.rb +12 -0
  199. data/vendor/rails/activerecord/test/cases/associations/belongs_to_associations_test.rb +102 -22
  200. data/vendor/rails/activerecord/test/cases/associations/eager_load_nested_include_test.rb +5 -5
  201. data/vendor/rails/activerecord/test/cases/associations/eager_test.rb +12 -0
  202. data/vendor/rails/activerecord/test/cases/associations/habtm_join_table_test.rb +56 -0
  203. data/vendor/rails/activerecord/test/cases/associations/has_many_associations_test.rb +62 -2
  204. data/vendor/rails/activerecord/test/cases/associations/has_many_through_associations_test.rb +46 -1
  205. data/vendor/rails/activerecord/test/cases/associations/has_one_through_associations_test.rb +18 -1
  206. data/vendor/rails/activerecord/test/cases/associations/inner_join_association_test.rb +5 -0
  207. data/vendor/rails/activerecord/test/cases/associations/join_model_test.rb +4 -4
  208. data/vendor/rails/activerecord/test/cases/autosave_association_test.rb +22 -0
  209. data/vendor/rails/activerecord/test/cases/base_test.rb +51 -6
  210. data/vendor/rails/activerecord/test/cases/calculations_test.rb +14 -14
  211. data/vendor/rails/activerecord/test/cases/column_definition_test.rb +34 -0
  212. data/vendor/rails/activerecord/test/cases/copy_table_test_sqlite.rb +5 -5
  213. data/vendor/rails/activerecord/test/cases/dirty_test.rb +10 -0
  214. data/vendor/rails/activerecord/test/cases/finder_test.rb +21 -50
  215. data/vendor/rails/activerecord/test/cases/fixtures_test.rb +6 -1
  216. data/vendor/rails/activerecord/test/cases/helper.rb +1 -2
  217. data/vendor/rails/activerecord/test/cases/i18n_test.rb +5 -0
  218. data/vendor/rails/activerecord/test/cases/json_serialization_test.rb +57 -57
  219. data/vendor/rails/activerecord/test/cases/method_scoping_test.rb +14 -4
  220. data/vendor/rails/activerecord/test/cases/migration_test.rb +39 -11
  221. data/vendor/rails/activerecord/test/cases/modules_test.rb +42 -0
  222. data/vendor/rails/activerecord/test/cases/named_scope_test.rb +6 -4
  223. data/vendor/rails/activerecord/test/cases/pk_test.rb +18 -0
  224. data/vendor/rails/activerecord/test/cases/reflection_test.rb +7 -7
  225. data/vendor/rails/activerecord/test/cases/schema_dumper_test.rb +35 -7
  226. data/vendor/rails/activerecord/test/cases/schema_test_postgresql.rb +76 -0
  227. data/vendor/rails/activerecord/test/cases/timestamp_test.rb +75 -0
  228. data/vendor/rails/activerecord/test/cases/validations_i18n_test.rb +656 -624
  229. data/vendor/rails/activerecord/test/cases/validations_test.rb +12 -2
  230. data/vendor/rails/activerecord/test/cases/xml_serialization_test.rb +20 -0
  231. data/vendor/rails/activerecord/test/fixtures/fixture_database.sqlite +0 -0
  232. data/vendor/rails/activerecord/test/fixtures/fixture_database.sqlite3 +0 -0
  233. data/vendor/rails/activerecord/test/fixtures/fixture_database_2.sqlite +0 -0
  234. data/vendor/rails/activerecord/test/fixtures/fixture_database_2.sqlite3 +0 -0
  235. data/vendor/rails/activerecord/test/fixtures/posts.yml +3 -0
  236. data/vendor/rails/activerecord/test/models/author.rb +5 -0
  237. data/vendor/rails/activerecord/test/models/comment.rb +5 -1
  238. data/vendor/rails/activerecord/test/models/company.rb +9 -7
  239. data/vendor/rails/activerecord/test/models/company_in_module.rb +1 -1
  240. data/vendor/rails/activerecord/test/models/contract.rb +5 -0
  241. data/vendor/rails/activerecord/test/models/developer.rb +10 -0
  242. data/vendor/rails/activerecord/test/models/essay.rb +3 -0
  243. data/vendor/rails/activerecord/test/models/organization.rb +2 -0
  244. data/vendor/rails/activerecord/test/models/pet.rb +1 -1
  245. data/vendor/rails/activerecord/test/models/project.rb +1 -1
  246. data/vendor/rails/activerecord/test/models/reply.rb +2 -1
  247. data/vendor/rails/activerecord/test/models/topic.rb +1 -2
  248. data/vendor/rails/activerecord/test/models/toy.rb +2 -0
  249. data/vendor/rails/activerecord/test/schema/postgresql_specific_schema.rb +13 -2
  250. data/vendor/rails/activerecord/test/schema/schema.rb +19 -0
  251. data/vendor/rails/activeresource/CHANGELOG +16 -0
  252. data/vendor/rails/activeresource/Rakefile +3 -2
  253. data/vendor/rails/activeresource/lib/active_resource/base.rb +89 -9
  254. data/vendor/rails/activeresource/lib/active_resource/connection.rb +73 -8
  255. data/vendor/rails/activeresource/lib/active_resource/exceptions.rb +66 -0
  256. data/vendor/rails/activeresource/lib/active_resource/formats/json_format.rb +2 -2
  257. data/vendor/rails/activeresource/lib/active_resource/validations.rb +20 -4
  258. data/vendor/rails/activeresource/lib/active_resource/version.rb +1 -1
  259. data/vendor/rails/activeresource/test/abstract_unit.rb +1 -3
  260. data/vendor/rails/activeresource/test/base/load_test.rb +16 -1
  261. data/vendor/rails/activeresource/test/base_errors_test.rb +56 -19
  262. data/vendor/rails/activeresource/test/base_test.rb +147 -0
  263. data/vendor/rails/activeresource/test/connection_test.rb +42 -0
  264. data/vendor/rails/activeresource/test/debug.log +7974 -0
  265. data/vendor/rails/activeresource/test/fixtures/proxy.rb +4 -0
  266. data/vendor/rails/activesupport/CHANGELOG +13 -0
  267. data/vendor/rails/activesupport/lib/active_support/all.rb +8 -0
  268. data/vendor/rails/activesupport/lib/active_support/cache.rb +14 -1
  269. data/vendor/rails/activesupport/lib/active_support/cache/mem_cache_store.rb +16 -10
  270. data/vendor/rails/activesupport/lib/active_support/cache/strategy/local_cache.rb +1 -1
  271. data/vendor/rails/activesupport/lib/active_support/core_ext/array/conversions.rb +1 -0
  272. data/vendor/rails/activesupport/lib/active_support/core_ext/date/calculations.rb +2 -1
  273. data/vendor/rails/activesupport/lib/active_support/core_ext/enumerable.rb +2 -4
  274. data/vendor/rails/activesupport/lib/active_support/core_ext/hash/conversions.rb +14 -4
  275. data/vendor/rails/activesupport/lib/active_support/core_ext/kernel/debugger.rb +4 -2
  276. data/vendor/rails/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb +2 -0
  277. data/vendor/rails/activesupport/lib/active_support/core_ext/module/delegation.rb +19 -5
  278. data/vendor/rails/activesupport/lib/active_support/core_ext/module/model_naming.rb +8 -6
  279. data/vendor/rails/activesupport/lib/active_support/core_ext/numeric/bytes.rb +15 -9
  280. data/vendor/rails/activesupport/lib/active_support/core_ext/string.rb +1 -0
  281. data/vendor/rails/activesupport/lib/active_support/core_ext/string/access.rb +29 -5
  282. data/vendor/rails/activesupport/lib/active_support/core_ext/string/bytesize.rb +5 -0
  283. data/vendor/rails/activesupport/lib/active_support/core_ext/time/calculations.rb +7 -7
  284. data/vendor/rails/activesupport/lib/active_support/deprecation.rb +9 -9
  285. data/vendor/rails/activesupport/lib/active_support/duration.rb +4 -2
  286. data/vendor/rails/activesupport/lib/active_support/json.rb +1 -22
  287. data/vendor/rails/activesupport/lib/active_support/json/backends/jsongem.rb +38 -0
  288. data/vendor/rails/activesupport/lib/active_support/json/backends/yaml.rb +88 -0
  289. data/vendor/rails/activesupport/lib/active_support/json/decoding.rb +23 -72
  290. data/vendor/rails/activesupport/lib/active_support/json/encoders/date.rb +9 -8
  291. data/vendor/rails/activesupport/lib/active_support/json/encoders/date_time.rb +9 -8
  292. data/vendor/rails/activesupport/lib/active_support/json/encoders/enumerable.rb +14 -9
  293. data/vendor/rails/activesupport/lib/active_support/json/encoders/false_class.rb +4 -2
  294. data/vendor/rails/activesupport/lib/active_support/json/encoders/hash.rb +21 -11
  295. data/vendor/rails/activesupport/lib/active_support/json/encoders/nil_class.rb +4 -2
  296. data/vendor/rails/activesupport/lib/active_support/json/encoders/numeric.rb +16 -0
  297. data/vendor/rails/activesupport/lib/active_support/json/encoders/object.rb +6 -2
  298. data/vendor/rails/activesupport/lib/active_support/json/encoders/regexp.rb +4 -0
  299. data/vendor/rails/activesupport/lib/active_support/json/encoders/string.rb +5 -32
  300. data/vendor/rails/activesupport/lib/active_support/json/encoders/symbol.rb +2 -2
  301. data/vendor/rails/activesupport/lib/active_support/json/encoders/time.rb +9 -8
  302. data/vendor/rails/activesupport/lib/active_support/json/encoders/true_class.rb +4 -2
  303. data/vendor/rails/activesupport/lib/active_support/json/encoding.rb +80 -9
  304. data/vendor/rails/activesupport/lib/active_support/memoizable.rb +1 -1
  305. data/vendor/rails/activesupport/lib/active_support/message_verifier.rb +16 -3
  306. data/vendor/rails/activesupport/lib/active_support/multibyte.rb +30 -6
  307. data/vendor/rails/activesupport/lib/active_support/multibyte/chars.rb +23 -17
  308. data/vendor/rails/activesupport/lib/active_support/multibyte/utils.rb +61 -0
  309. data/vendor/rails/activesupport/lib/active_support/ordered_hash.rb +28 -0
  310. data/vendor/rails/activesupport/lib/active_support/test_case.rb +9 -8
  311. data/vendor/rails/activesupport/lib/active_support/testing/deprecation.rb +2 -0
  312. data/vendor/rails/activesupport/lib/active_support/time_with_zone.rb +9 -8
  313. data/vendor/rails/activesupport/lib/active_support/vendor.rb +6 -7
  314. data/vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb +0 -1
  315. data/vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb +0 -1
  316. data/vendor/rails/activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb +0 -1
  317. data/vendor/rails/activesupport/lib/active_support/vendor/{memcache-client-1.6.5 → memcache-client-1.7.4}/memcache.rb +242 -70
  318. data/vendor/rails/activesupport/lib/active_support/version.rb +1 -1
  319. data/vendor/rails/activesupport/lib/active_support/xml_mini/jdom.rb +162 -0
  320. data/vendor/rails/railties/CHANGELOG +10 -0
  321. data/vendor/rails/railties/Rakefile +13 -9
  322. data/vendor/rails/railties/bin/about +2 -2
  323. data/vendor/rails/railties/bin/console +1 -1
  324. data/vendor/rails/railties/bin/dbconsole +1 -1
  325. data/vendor/rails/railties/bin/destroy +1 -1
  326. data/vendor/rails/railties/bin/generate +1 -1
  327. data/vendor/rails/railties/bin/performance/benchmarker +1 -1
  328. data/vendor/rails/railties/bin/performance/profiler +1 -1
  329. data/vendor/rails/railties/bin/plugin +1 -1
  330. data/vendor/rails/railties/bin/runner +1 -1
  331. data/vendor/rails/railties/bin/server +1 -1
  332. data/vendor/rails/railties/builtin/rails_info/rails/info.rb +4 -2
  333. data/vendor/rails/railties/configs/initializers/new_rails_defaults.rb +2 -0
  334. data/vendor/rails/railties/configs/routes.rb +1 -1
  335. data/vendor/rails/railties/configs/seeds.rb +7 -0
  336. data/vendor/rails/railties/environments/boot.rb +1 -1
  337. data/vendor/rails/railties/guides/files/javascripts/code_highlighter.js +188 -0
  338. data/vendor/rails/railties/guides/files/javascripts/guides.js +8 -0
  339. data/vendor/rails/railties/guides/files/javascripts/highlighters.js +90 -0
  340. data/vendor/rails/railties/guides/files/stylesheets/main.css +441 -0
  341. data/vendor/rails/railties/guides/files/stylesheets/print.css +52 -0
  342. data/vendor/rails/railties/guides/files/stylesheets/reset.css +43 -0
  343. data/vendor/rails/railties/guides/files/stylesheets/style.css +13 -0
  344. data/vendor/rails/railties/guides/files/stylesheets/syntax.css +31 -0
  345. data/vendor/rails/railties/guides/images/belongs_to.png +0 -0
  346. data/vendor/rails/railties/guides/images/book_icon.gif +0 -0
  347. data/vendor/rails/railties/guides/images/bullet.gif +0 -0
  348. data/vendor/rails/railties/guides/images/chapters_icon.gif +0 -0
  349. data/vendor/rails/railties/guides/images/check_bullet.gif +0 -0
  350. data/vendor/rails/railties/guides/images/credits_pic_blank.gif +0 -0
  351. data/vendor/rails/railties/guides/images/csrf.png +0 -0
  352. data/vendor/rails/railties/guides/images/customized_error_messages.png +0 -0
  353. data/vendor/rails/railties/guides/images/error_messages.png +0 -0
  354. data/vendor/rails/railties/guides/images/feature_tile.gif +0 -0
  355. data/vendor/rails/railties/guides/images/footer_tile.gif +0 -0
  356. data/vendor/rails/railties/guides/images/fxn.jpg +0 -0
  357. data/vendor/rails/railties/guides/images/grey_bullet.gif +0 -0
  358. data/vendor/rails/railties/guides/images/habtm.png +0 -0
  359. data/vendor/rails/railties/guides/images/has_many.png +0 -0
  360. data/vendor/rails/railties/guides/images/has_many_through.png +0 -0
  361. data/vendor/rails/railties/guides/images/has_one.png +0 -0
  362. data/vendor/rails/railties/guides/images/has_one_through.png +0 -0
  363. data/vendor/rails/railties/guides/images/header_backdrop.png +0 -0
  364. data/vendor/rails/railties/guides/images/header_tile.gif +0 -0
  365. data/vendor/rails/railties/guides/images/i18n/demo_localized_pirate.png +0 -0
  366. data/vendor/rails/railties/guides/images/i18n/demo_translated_en.png +0 -0
  367. data/vendor/rails/railties/guides/images/i18n/demo_translated_pirate.png +0 -0
  368. data/vendor/rails/railties/guides/images/i18n/demo_translation_missing.png +0 -0
  369. data/vendor/rails/railties/guides/images/i18n/demo_untranslated.png +0 -0
  370. data/vendor/rails/railties/guides/images/icons/README +5 -0
  371. data/vendor/rails/railties/guides/images/icons/callouts/1.png +0 -0
  372. data/vendor/rails/railties/guides/images/icons/callouts/10.png +0 -0
  373. data/vendor/rails/railties/guides/images/icons/callouts/11.png +0 -0
  374. data/vendor/rails/railties/guides/images/icons/callouts/12.png +0 -0
  375. data/vendor/rails/railties/guides/images/icons/callouts/13.png +0 -0
  376. data/vendor/rails/railties/guides/images/icons/callouts/14.png +0 -0
  377. data/vendor/rails/railties/guides/images/icons/callouts/15.png +0 -0
  378. data/vendor/rails/railties/guides/images/icons/callouts/2.png +0 -0
  379. data/vendor/rails/railties/guides/images/icons/callouts/3.png +0 -0
  380. data/vendor/rails/railties/guides/images/icons/callouts/4.png +0 -0
  381. data/vendor/rails/railties/guides/images/icons/callouts/5.png +0 -0
  382. data/vendor/rails/railties/guides/images/icons/callouts/6.png +0 -0
  383. data/vendor/rails/railties/guides/images/icons/callouts/7.png +0 -0
  384. data/vendor/rails/railties/guides/images/icons/callouts/8.png +0 -0
  385. data/vendor/rails/railties/guides/images/icons/callouts/9.png +0 -0
  386. data/vendor/rails/railties/guides/images/icons/caution.png +0 -0
  387. data/vendor/rails/railties/guides/images/icons/example.png +0 -0
  388. data/vendor/rails/railties/guides/images/icons/home.png +0 -0
  389. data/vendor/rails/railties/guides/images/icons/important.png +0 -0
  390. data/vendor/rails/railties/guides/images/icons/next.png +0 -0
  391. data/vendor/rails/railties/guides/images/icons/note.png +0 -0
  392. data/vendor/rails/railties/guides/images/icons/prev.png +0 -0
  393. data/vendor/rails/railties/guides/images/icons/tip.png +0 -0
  394. data/vendor/rails/railties/guides/images/icons/up.png +0 -0
  395. data/vendor/rails/railties/guides/images/icons/warning.png +0 -0
  396. data/vendor/rails/railties/guides/images/nav_arrow.gif +0 -0
  397. data/vendor/rails/railties/guides/images/polymorphic.png +0 -0
  398. data/vendor/rails/railties/guides/images/posts_index.png +0 -0
  399. data/vendor/rails/railties/guides/images/rails_guides_logo.gif +0 -0
  400. data/vendor/rails/railties/guides/images/rails_logo_remix.gif +0 -0
  401. data/vendor/rails/railties/guides/images/rails_welcome.png +0 -0
  402. data/vendor/rails/railties/guides/images/session_fixation.png +0 -0
  403. data/vendor/rails/railties/guides/images/tab_grey.gif +0 -0
  404. data/vendor/rails/railties/guides/images/tab_info.gif +0 -0
  405. data/vendor/rails/railties/guides/images/tab_note.gif +0 -0
  406. data/vendor/rails/railties/guides/images/tab_red.gif +0 -0
  407. data/vendor/rails/railties/guides/images/tab_yellow.gif +0 -0
  408. data/vendor/rails/railties/guides/images/tab_yellow.png +0 -0
  409. data/vendor/rails/railties/guides/images/validation_error_messages.png +0 -0
  410. data/vendor/rails/railties/guides/rails_guides.rb +42 -0
  411. data/vendor/rails/railties/guides/rails_guides/generator.rb +138 -0
  412. data/vendor/rails/railties/guides/rails_guides/helpers.rb +34 -0
  413. data/vendor/rails/railties/guides/rails_guides/indexer.rb +55 -0
  414. data/vendor/rails/railties/guides/rails_guides/textile_extensions.rb +41 -0
  415. data/vendor/rails/railties/guides/source/2_2_release_notes.textile +422 -0
  416. data/vendor/rails/railties/guides/source/2_3_release_notes.textile +610 -0
  417. data/vendor/rails/railties/guides/source/action_controller_overview.textile +776 -0
  418. data/vendor/rails/railties/guides/source/action_mailer_basics.textile +424 -0
  419. data/vendor/rails/railties/guides/source/active_record_basics.textile +135 -0
  420. data/vendor/rails/railties/guides/source/active_record_querying.textile +969 -0
  421. data/vendor/rails/railties/guides/source/activerecord_validations_callbacks.textile +1086 -0
  422. data/vendor/rails/railties/guides/source/association_basics.textile +1781 -0
  423. data/vendor/rails/railties/guides/source/caching_with_rails.textile +524 -0
  424. data/vendor/rails/railties/guides/source/command_line.textile +589 -0
  425. data/vendor/rails/railties/guides/source/configuring.textile +234 -0
  426. data/vendor/rails/railties/guides/source/contribute.textile +71 -0
  427. data/vendor/rails/railties/guides/source/contributing_to_rails.textile +239 -0
  428. data/vendor/rails/railties/guides/source/credits.erb.textile +52 -0
  429. data/vendor/rails/railties/guides/source/debugging_rails_applications.textile +709 -0
  430. data/vendor/rails/railties/guides/source/form_helpers.textile +766 -0
  431. data/vendor/rails/railties/guides/source/getting_started.textile +1297 -0
  432. data/vendor/rails/railties/guides/source/i18n.textile +912 -0
  433. data/vendor/rails/railties/guides/source/index.erb.textile +124 -0
  434. data/vendor/rails/railties/guides/source/layout.html.erb +103 -0
  435. data/vendor/rails/railties/guides/source/layouts_and_rendering.textile +979 -0
  436. data/vendor/rails/railties/guides/source/migrations.textile +591 -0
  437. data/vendor/rails/railties/guides/source/nested_model_forms.textile +222 -0
  438. data/vendor/rails/railties/guides/source/performance_testing.textile +531 -0
  439. data/vendor/rails/railties/guides/source/plugins.textile +1512 -0
  440. data/vendor/rails/railties/guides/source/rails_on_rack.textile +309 -0
  441. data/vendor/rails/railties/guides/source/routing.textile +903 -0
  442. data/vendor/rails/railties/guides/source/security.textile +986 -0
  443. data/vendor/rails/railties/guides/source/testing.textile +951 -0
  444. data/vendor/rails/railties/lib/commands/dbconsole.rb +8 -4
  445. data/vendor/rails/railties/lib/commands/performance/profiler.rb +1 -1
  446. data/vendor/rails/railties/lib/initializer.rb +27 -4
  447. data/vendor/rails/railties/lib/rails/gem_dependency.rb +35 -6
  448. data/vendor/rails/railties/lib/rails/plugin.rb +12 -0
  449. data/vendor/rails/railties/lib/rails/plugin/loader.rb +7 -0
  450. data/vendor/rails/railties/lib/rails/rack/metal.rb +1 -1
  451. data/vendor/rails/railties/lib/rails/version.rb +1 -1
  452. data/vendor/rails/railties/lib/rails_generator/base.rb +1 -1
  453. data/vendor/rails/railties/lib/rails_generator/generators/applications/app/app_generator.rb +5 -0
  454. data/vendor/rails/railties/lib/rails_generator/generators/applications/app/template_runner.rb +1 -1
  455. data/vendor/rails/railties/lib/rails_generator/generators/components/model/model_generator.rb +9 -2
  456. data/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb +1 -0
  457. data/vendor/rails/railties/lib/tasks/databases.rake +17 -4
  458. data/vendor/rails/railties/lib/tasks/gems.rake +19 -6
  459. data/vendor/rails/railties/lib/tasks/routes.rake +4 -3
  460. data/vendor/rails/railties/lib/test_help.rb +4 -1
  461. metadata +158 -58
  462. data/spec/lib/local_time_spec.rb +0 -40
  463. data/vendor/rails/actionpack/lib/action_controller/rewindable_input.rb +0 -28
  464. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack.rb +0 -89
  465. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/adapter/camping.rb +0 -22
  466. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/abstract/handler.rb +0 -37
  467. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/abstract/request.rb +0 -37
  468. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/basic.rb +0 -58
  469. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/md5.rb +0 -124
  470. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/nonce.rb +0 -51
  471. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/params.rb +0 -55
  472. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/request.rb +0 -40
  473. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/openid.rb +0 -480
  474. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/builder.rb +0 -63
  475. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/cascade.rb +0 -36
  476. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/chunked.rb +0 -49
  477. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/commonlogger.rb +0 -61
  478. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/conditionalget.rb +0 -45
  479. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/content_length.rb +0 -29
  480. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/content_type.rb +0 -23
  481. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/deflater.rb +0 -85
  482. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/directory.rb +0 -153
  483. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/file.rb +0 -88
  484. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler.rb +0 -48
  485. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/cgi.rb +0 -61
  486. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/evented_mongrel.rb +0 -8
  487. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/fastcgi.rb +0 -89
  488. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/lsws.rb +0 -55
  489. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/mongrel.rb +0 -84
  490. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/scgi.rb +0 -59
  491. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/swiftiplied_mongrel.rb +0 -8
  492. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/thin.rb +0 -18
  493. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/webrick.rb +0 -67
  494. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/head.rb +0 -19
  495. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/lint.rb +0 -462
  496. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/lobster.rb +0 -65
  497. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/lock.rb +0 -16
  498. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/methodoverride.rb +0 -27
  499. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/mime.rb +0 -204
  500. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/mock.rb +0 -160
  501. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/recursive.rb +0 -57
  502. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/reloader.rb +0 -64
  503. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/request.rb +0 -241
  504. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/response.rb +0 -179
  505. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/abstract/id.rb +0 -142
  506. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/cookie.rb +0 -91
  507. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/memcache.rb +0 -109
  508. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/pool.rb +0 -100
  509. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/showexceptions.rb +0 -349
  510. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/showstatus.rb +0 -106
  511. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/static.rb +0 -38
  512. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/urlmap.rb +0 -55
  513. data/vendor/rails/actionpack/lib/action_controller/vendor/rack-1.0/rack/utils.rb +0 -392
@@ -0,0 +1,1781 @@
1
+ h2. A Guide to Active Record Associations
2
+
3
+ This guide covers the association features of Active Record. By referring to this guide, you will be able to:
4
+
5
+ * Declare associations between Active Record models
6
+ * Understand the various types of Active Record associations
7
+ * Use the methods added to your models by creating associations
8
+
9
+ endprologue.
10
+
11
+ h3. Why Associations?
12
+
13
+ Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:
14
+
15
+ <ruby>
16
+ class Customer < ActiveRecord::Base
17
+ end
18
+
19
+ class Order < ActiveRecord::Base
20
+ end
21
+ </ruby>
22
+
23
+ Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:
24
+
25
+ <ruby>
26
+ @order = Order.create(:order_date => Time.now,
27
+ :customer_id => @customer.id)
28
+ </ruby>
29
+
30
+ Or consider deleting a customer, and ensuring that all of its orders get deleted as well:
31
+
32
+ <ruby>
33
+ @orders = Order.find_by_customer_id(@customer.id)
34
+ @orders.each do |order|
35
+ order.destroy
36
+ end
37
+ @customer.destroy
38
+ </ruby>
39
+
40
+ With Active Record associations, we can streamline these -- and other -- operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:
41
+
42
+ <ruby>
43
+ class Customer < ActiveRecord::Base
44
+ has_many :orders, :dependent => :destroy
45
+ end
46
+
47
+ class Order < ActiveRecord::Base
48
+ belongs_to :customer
49
+ end
50
+ </ruby>
51
+
52
+ With this change, creating a new order for a particular customer is easier:
53
+
54
+ <ruby>
55
+ @order = @customer.orders.create(:order_date => Time.now)
56
+ </ruby>
57
+
58
+ Deleting a customer and all of its orders is _much_ easier:
59
+
60
+ <ruby>
61
+ @customer.destroy
62
+ </ruby>
63
+
64
+ To learn more about the different types of associations, read the next section of this guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.
65
+
66
+ h3. The Types of Associations
67
+
68
+ In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:
69
+
70
+ * +belongs_to+
71
+ * +has_one+
72
+ * +has_many+
73
+ * +has_many :through+
74
+ * +has_one :through+
75
+ * +has_and_belongs_to_many+
76
+
77
+ In the remainder of this guide, you'll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.
78
+
79
+ h4. The +belongs_to+ Association
80
+
81
+ A +belongs_to+ association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way:
82
+
83
+ <ruby>
84
+ class Order < ActiveRecord::Base
85
+ belongs_to :customer
86
+ end
87
+ </ruby>
88
+
89
+ !images/belongs_to.png(belongs_to Association Diagram)!
90
+
91
+ h4. The +has_one+ Association
92
+
93
+ A +has_one+ association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:
94
+
95
+ <ruby>
96
+ class Supplier < ActiveRecord::Base
97
+ has_one :account
98
+ end
99
+ </ruby>
100
+
101
+ !images/has_one.png(has_one Association Diagram)!
102
+
103
+ h4. The +has_many+ Association
104
+
105
+ A +has_many+ association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a +belongs_to+ association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:
106
+
107
+ <ruby>
108
+ class Customer < ActiveRecord::Base
109
+ has_many :orders
110
+ end
111
+ </ruby>
112
+
113
+ NOTE: The name of the other model is pluralized when declaring a +has_many+ association.
114
+
115
+ !images/has_many.png(has_many Association Diagram)!
116
+
117
+ h4. The +has_many :through+ Association
118
+
119
+ A +has_many :through+ association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding _through_ a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:
120
+
121
+ <ruby>
122
+ class Physician < ActiveRecord::Base
123
+ has_many :appointments
124
+ has_many :patients, :through => :appointments
125
+ end
126
+
127
+ class Appointment < ActiveRecord::Base
128
+ belongs_to :physician
129
+ belongs_to :patient
130
+ end
131
+
132
+ class Patient < ActiveRecord::Base
133
+ has_many :appointments
134
+ has_many :physicians, :through => :appointments
135
+ end
136
+ </ruby>
137
+
138
+ !images/has_many_through.png(has_many :through Association Diagram)!
139
+
140
+ The +has_many :through+ association is also useful for setting up "shortcuts" through nested +has_many+ associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:
141
+
142
+ <ruby>
143
+ class Document < ActiveRecord::Base
144
+ has_many :sections
145
+ has_many :paragraphs, :through => :sections
146
+ end
147
+
148
+ class Section < ActiveRecord::Base
149
+ belongs_to :document
150
+ has_many :paragraphs
151
+ end
152
+
153
+ class Paragraph < ActiveRecord::Base
154
+ belongs_to :section
155
+ end
156
+ </ruby>
157
+
158
+ h4. The +has_one :through+ Association
159
+
160
+ A +has_one :through+ association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding _through_ a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:
161
+
162
+ <ruby>
163
+ class Supplier < ActiveRecord::Base
164
+ has_one :account
165
+ has_one :account_history, :through => :account
166
+ end
167
+
168
+ class Account < ActiveRecord::Base
169
+ belongs_to :supplier
170
+ has_one :account_history
171
+ end
172
+
173
+ class AccountHistory < ActiveRecord::Base
174
+ belongs_to :account
175
+ end
176
+ </ruby>
177
+
178
+ !images/has_one_through.png(has_one :through Association Diagram)!
179
+
180
+ h4. The +has_and_belongs_to_many+ Association
181
+
182
+ A +has_and_belongs_to_many+ association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:
183
+
184
+ <ruby>
185
+ class Assembly < ActiveRecord::Base
186
+ has_and_belongs_to_many :parts
187
+ end
188
+
189
+ class Part < ActiveRecord::Base
190
+ has_and_belongs_to_many :assemblies
191
+ end
192
+ </ruby>
193
+
194
+ !images/habtm.png(has_and_belongs_to_many Association Diagram)!
195
+
196
+ h4. Choosing Between +belongs_to+ and +has_one+
197
+
198
+ If you want to set up a 1–1 relationship between two models, you'll need to add +belongs_to+ to one, and +has_one+ to the other. How do you know which is which?
199
+
200
+ The distinction is in where you place the foreign key (it goes on the table for the class declaring the +belongs_to+ association), but you should give some thought to the actual meaning of the data as well. The +has_one+ relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
201
+
202
+ <ruby>
203
+ class Supplier < ActiveRecord::Base
204
+ has_one :account
205
+ end
206
+
207
+ class Account < ActiveRecord::Base
208
+ belongs_to :supplier
209
+ end
210
+ </ruby>
211
+
212
+ The corresponding migration might look like this:
213
+
214
+ <ruby>
215
+ class CreateSuppliers < ActiveRecord::Migration
216
+ def self.up
217
+ create_table :suppliers do |t|
218
+ t.string :name
219
+ t.timestamps
220
+ end
221
+
222
+ create_table :accounts do |t|
223
+ t.integer :supplier_id
224
+ t.string :account_number
225
+ t.timestamps
226
+ end
227
+ end
228
+
229
+ def self.down
230
+ drop_table :accounts
231
+ drop_table :suppliers
232
+ end
233
+ end
234
+ </ruby>
235
+
236
+ NOTE: Using +t.integer :supplier_id+ makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using +t.references :supplier+ instead.
237
+
238
+ h4. Choosing Between +has_many :through+ and +has_and_belongs_to_many+
239
+
240
+ Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use +has_and_belongs_to_many+, which allows you to make the association directly:
241
+
242
+ <ruby>
243
+ class Assembly < ActiveRecord::Base
244
+ has_and_belongs_to_many :parts
245
+ end
246
+
247
+ class Part < ActiveRecord::Base
248
+ has_and_belongs_to_many :assemblies
249
+ end
250
+ </ruby>
251
+
252
+ The second way to declare a many-to-many relationship is to use +has_many :through+. This makes the association indirectly, through a join model:
253
+
254
+ <ruby>
255
+ class Assembly < ActiveRecord::Base
256
+ has_many :manifests
257
+ has_many :parts, :through => :manifests
258
+ end
259
+
260
+ class Manifest < ActiveRecord::Base
261
+ belongs_to :assembly
262
+ belongs_to :part
263
+ end
264
+
265
+ class Part < ActiveRecord::Base
266
+ has_many :manifests
267
+ has_many :assemblies, :through => :manifests
268
+ end
269
+ </ruby>
270
+
271
+ The simplest rule of thumb is that you should set up a +has_many :through+ relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a +has_and_belongs_to_many+ relationship (though you'll need to remember to create the joining table in the database).
272
+
273
+ You should use +has_many :through+ if you need validations, callbacks, or extra attributes on the join model.
274
+
275
+ h4. Polymorphic Associations
276
+
277
+ A slightly more advanced twist on associations is the _polymorphic association_. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:
278
+
279
+ <ruby>
280
+ class Picture < ActiveRecord::Base
281
+ belongs_to :imageable, :polymorphic => true
282
+ end
283
+
284
+ class Employee < ActiveRecord::Base
285
+ has_many :pictures, :as => :imageable
286
+ end
287
+
288
+ class Product < ActiveRecord::Base
289
+ has_many :pictures, :as => :imageable
290
+ end
291
+ </ruby>
292
+
293
+ You can think of a polymorphic +belongs_to+ declaration as setting up an interface that any other model can use. From an instance of the +Employee+ model, you can retrieve a collection of pictures: +@employee.pictures+.
294
+
295
+ Similarly, you can retrieve +@product.pictures+.
296
+
297
+ If you have an instance of the +Picture+ model, you can get to its parent via +@picture.imageable+. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:
298
+
299
+ <ruby>
300
+ class CreatePictures < ActiveRecord::Migration
301
+ def self.up
302
+ create_table :pictures do |t|
303
+ t.string :name
304
+ t.integer :imageable_id
305
+ t.string :imageable_type
306
+ t.timestamps
307
+ end
308
+ end
309
+
310
+ def self.down
311
+ drop_table :pictures
312
+ end
313
+ end
314
+ </ruby>
315
+
316
+ This migration can be simplified by using the +t.references+ form:
317
+
318
+ <ruby>
319
+ class CreatePictures < ActiveRecord::Migration
320
+ def self.up
321
+ create_table :pictures do |t|
322
+ t.string :name
323
+ t.references :imageable, :polymorphic => true
324
+ t.timestamps
325
+ end
326
+ end
327
+
328
+ def self.down
329
+ drop_table :pictures
330
+ end
331
+ end
332
+ </ruby>
333
+
334
+ !images/polymorphic.png(Polymorphic Association Diagram)!
335
+
336
+ h4. Self Joins
337
+
338
+ In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:
339
+
340
+ <ruby>
341
+ class Employee < ActiveRecord::Base
342
+ has_many :subordinates, :class_name => "Employee",
343
+ :foreign_key => "manager_id"
344
+ belongs_to :manager, :class_name => "Employee"
345
+ end
346
+ </ruby>
347
+
348
+ With this setup, you can retrieve +@employee.subordinates+ and +@employee.manager+.
349
+
350
+ h3. Tips, Tricks, and Warnings
351
+
352
+ Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
353
+
354
+ * Controlling caching
355
+ * Avoiding name collisions
356
+ * Updating the schema
357
+ * Controlling association scope
358
+
359
+ h4. Controlling Caching
360
+
361
+ All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:
362
+
363
+ <ruby>
364
+ customer.orders # retrieves orders from the database
365
+ customer.orders.size # uses the cached copy of orders
366
+ customer.orders.empty? # uses the cached copy of orders
367
+ </ruby>
368
+
369
+ But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass +true+ to the association call:
370
+
371
+ <ruby>
372
+ customer.orders # retrieves orders from the database
373
+ customer.orders.size # uses the cached copy of orders
374
+ customer.orders(true).empty? # discards the cached copy of orders
375
+ # and goes back to the database
376
+ </ruby>
377
+
378
+ h4. Avoiding Name Collisions
379
+
380
+ You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of +ActiveRecord::Base+. The association method would override the base method and break things. For instance, +attributes+ or +connection+ are bad names for associations.
381
+
382
+ h4. Updating the Schema
383
+
384
+ Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For +belongs_to+ associations you need to create foreign keys, and for +has_and_belongs_to_many+ associations you need to create the appropriate join table.
385
+
386
+ h5. Creating Foreign Keys for +belongs_to+ Associations
387
+
388
+ When you declare a +belongs_to+ association, you need to create foreign keys as appropriate. For example, consider this model:
389
+
390
+ <ruby>
391
+ class Order < ActiveRecord::Base
392
+ belongs_to :customer
393
+ end
394
+ </ruby>
395
+
396
+ This declaration needs to be backed up by the proper foreign key declaration on the orders table:
397
+
398
+ <ruby>
399
+ class CreateOrders < ActiveRecord::Migration
400
+ def self.up
401
+ create_table :orders do |t|
402
+ t.datetime :order_date
403
+ t.string :order_number
404
+ t.integer :customer_id
405
+ end
406
+ end
407
+
408
+ def self.down
409
+ drop_table :orders
410
+ end
411
+ end
412
+ </ruby>
413
+
414
+ If you create an association some time after you build the underlying model, you need to remember to create an +add_column+ migration to provide the necessary foreign key.
415
+
416
+ h5. Creating Join Tables for +has_and_belongs_to_many+ Associations
417
+
418
+ If you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record creates the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
419
+
420
+ WARNING: The precedence between model names is calculated using the +<+ operator for +String+. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers" (because the underscore '_' is lexicographically _less_ than 's' in common encodings).
421
+
422
+ Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
423
+
424
+ <ruby>
425
+ class Assembly < ActiveRecord::Base
426
+ has_and_belongs_to_many :parts
427
+ end
428
+
429
+ class Part < ActiveRecord::Base
430
+ has_and_belongs_to_many :assemblies
431
+ end
432
+ </ruby>
433
+
434
+ These need to be backed up by a migration to create the +assemblies_parts+ table. This table should be created without a primary key:
435
+
436
+ <ruby>
437
+ class CreateAssemblyPartJoinTable < ActiveRecord::Migration
438
+ def self.up
439
+ create_table :assemblies_parts, :id => false do |t|
440
+ t.integer :assembly_id
441
+ t.integer :part_id
442
+ end
443
+ end
444
+
445
+ def self.down
446
+ drop_table :assemblies_parts
447
+ end
448
+ end
449
+ </ruby>
450
+
451
+ We pass +:id => false+ to +create_table+ because that table does not represent a model. That's required for the association to work properly. If you observe any strange behaviour in a +has_and_belongs_to_many+ association like mangled models IDs, or exceptions about conflicting IDs chances are you forgot that bit.
452
+
453
+ h4. Controlling Association Scope
454
+
455
+ By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example:
456
+
457
+ <ruby>
458
+ module MyApplication
459
+ module Business
460
+ class Supplier < ActiveRecord::Base
461
+ has_one :account
462
+ end
463
+
464
+ class Account < ActiveRecord::Base
465
+ belongs_to :supplier
466
+ end
467
+ end
468
+ end
469
+ </ruby>
470
+
471
+ This will work fine, because both the +Supplier+ and the +Account+ class are defined within the same scope. But the following will _not_ work, because +Supplier+ and +Account+ are defined in different scopes:
472
+
473
+ <ruby>
474
+ module MyApplication
475
+ module Business
476
+ class Supplier < ActiveRecord::Base
477
+ has_one :account
478
+ end
479
+ end
480
+
481
+ module Billing
482
+ class Account < ActiveRecord::Base
483
+ belongs_to :supplier
484
+ end
485
+ end
486
+ end
487
+ </ruby>
488
+
489
+ To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:
490
+
491
+ <ruby>
492
+ module MyApplication
493
+ module Business
494
+ class Supplier < ActiveRecord::Base
495
+ has_one :account,
496
+ :class_name => "MyApplication::Billing::Account"
497
+ end
498
+ end
499
+
500
+ module Billing
501
+ class Account < ActiveRecord::Base
502
+ belongs_to :supplier,
503
+ :class_name => "MyApplication::Business::Supplier"
504
+ end
505
+ end
506
+ end
507
+ </ruby>
508
+
509
+ h3. Detailed Association Reference
510
+
511
+ The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.
512
+
513
+ h4. +belongs_to+ Association Reference
514
+
515
+ The +belongs_to+ association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use +has_one+ instead.
516
+
517
+ h5. Methods Added by +belongs_to+
518
+
519
+ When you declare a +belongs_to+ association, the declaring class automatically gains four methods related to the association:
520
+
521
+ * <tt><em>association</em>(force_reload = false)</tt>
522
+ * <tt><em>association</em>=(associate)</tt>
523
+ * <tt>build_<em>association</em>(attributes = {})</tt>
524
+ * <tt>create_<em>association</em>(attributes = {})</tt>
525
+
526
+ In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to +belongs_to+. For example, given the declaration:
527
+
528
+ <ruby>
529
+ class Order < ActiveRecord::Base
530
+ belongs_to :customer
531
+ end
532
+ </ruby>
533
+
534
+ Each instance of the order model will have these methods:
535
+
536
+ <ruby>
537
+ customer
538
+ customer=
539
+ build_customer
540
+ create_customer
541
+ </ruby>
542
+
543
+ h6. _association_(force_reload = false)
544
+
545
+ The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.
546
+
547
+ <ruby>
548
+ @customer = @order.customer
549
+ </ruby>
550
+
551
+ If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument.
552
+
553
+ h6. _association_=(associate)
554
+
555
+ The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
556
+
557
+ <ruby>
558
+ @order.customer = @customer
559
+ </ruby>
560
+
561
+ h6. build_<em>association</em>(attributes = {})
562
+
563
+ The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
564
+
565
+ <ruby>
566
+ @customer = @order.build_customer(:customer_number => 123,
567
+ :customer_name => "John Doe")
568
+ </ruby>
569
+
570
+ h6. create_<em>association</em>(attributes = {})
571
+
572
+ The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
573
+
574
+ <ruby>
575
+ @customer = @order.create_customer(:customer_number => 123,
576
+ :customer_name => "John Doe")
577
+ </ruby>
578
+
579
+
580
+ h5. Options for +belongs_to+
581
+
582
+ In many situations, you can use the default behavior of +belongs_to+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +belongs_to+ association. For example, an association with several options might look like this:
583
+
584
+ <ruby>
585
+ class Order < ActiveRecord::Base
586
+ belongs_to :customer, :counter_cache => true,
587
+ :conditions => "active = 1"
588
+ end
589
+ </ruby>
590
+
591
+ The +belongs_to+ association supports these options:
592
+
593
+ * +:autosave+
594
+ * +:class_name+
595
+ * +:conditions+
596
+ * +:counter_cache+
597
+ * +:dependent+
598
+ * +:foreign_key+
599
+ * +:include+
600
+ * +:polymorphic+
601
+ * +:readonly+
602
+ * +:select+
603
+ * +:validate+
604
+
605
+ h6. +:autosave+
606
+
607
+ If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
608
+
609
+ h6. +:class_name+
610
+
611
+ If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is +Patron+, you'd set things up this way:
612
+
613
+ <ruby>
614
+ class Order < ActiveRecord::Base
615
+ belongs_to :customer, :class_name => "Patron"
616
+ end
617
+ </ruby>
618
+
619
+ h6. +:conditions+
620
+
621
+ The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
622
+
623
+ <ruby>
624
+ class Order < ActiveRecord::Base
625
+ belongs_to :customer, :conditions => "active = 1"
626
+ end
627
+ </ruby>
628
+
629
+ h6. +:counter_cache+
630
+
631
+ The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
632
+
633
+ <ruby>
634
+ class Order < ActiveRecord::Base
635
+ belongs_to :customer
636
+ end
637
+ class Customer < ActiveRecord::Base
638
+ has_many :orders
639
+ end
640
+ </ruby>
641
+
642
+ With these declarations, asking for the value of +@customer.orders.size+ requires making a call to the database to perform a +COUNT(*)+ query. To avoid this call, you can add a counter cache to the _belonging_ model:
643
+
644
+ <ruby>
645
+ class Order < ActiveRecord::Base
646
+ belongs_to :customer, :counter_cache => true
647
+ end
648
+ class Customer < ActiveRecord::Base
649
+ has_many :orders
650
+ end
651
+ </ruby>
652
+
653
+ With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +size+ method.
654
+
655
+ Although the +:counter_cache+ option is specified on the model that includes the +belongs_to+ declaration, the actual column must be added to the _associated_ model. In the case above, you would need to add a column named +orders_count+ to the +Customer+ model. You can override the default column name if you need to:
656
+
657
+ <ruby>
658
+ class Order < ActiveRecord::Base
659
+ belongs_to :customer, :counter_cache => :count_of_orders
660
+ end
661
+ class Customer < ActiveRecord::Base
662
+ has_many :orders
663
+ end
664
+ </ruby>
665
+
666
+ Counter cache columns are added to the containing model's list of read-only attributes through +attr_readonly+.
667
+
668
+ h6. +:dependent+
669
+
670
+ If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method.
671
+
672
+ WARNING: You should not specify this option on a +belongs_to+ association that is connected with a +has_many+ association on the other class. Doing so can lead to orphaned records in your database.
673
+
674
+ h6. +:foreign_key+
675
+
676
+ By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
677
+
678
+ <ruby>
679
+ class Order < ActiveRecord::Base
680
+ belongs_to :customer, :class_name => "Patron",
681
+ :foreign_key => "patron_id"
682
+ end
683
+ </ruby>
684
+
685
+ TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
686
+
687
+ h6. +:include+
688
+
689
+ You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
690
+
691
+ <ruby>
692
+ class LineItem < ActiveRecord::Base
693
+ belongs_to :order
694
+ end
695
+
696
+ class Order < ActiveRecord::Base
697
+ belongs_to :customer
698
+ has_many :line_items
699
+ end
700
+
701
+ class Customer < ActiveRecord::Base
702
+ has_many :orders
703
+ end
704
+ </ruby>
705
+
706
+ If you frequently retrieve customers directly from line items (+@line_item.order.customer+), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
707
+
708
+ <ruby>
709
+ class LineItem < ActiveRecord::Base
710
+ belongs_to :order, :include => :customer
711
+ end
712
+
713
+ class Order < ActiveRecord::Base
714
+ belongs_to :customer
715
+ has_many :line_items
716
+ end
717
+
718
+ class Customer < ActiveRecord::Base
719
+ has_many :orders
720
+ end
721
+ </ruby>
722
+
723
+ NOTE: There's no need to use +:include+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed.
724
+
725
+ h6. +:polymorphic+
726
+
727
+ Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
728
+
729
+ h6. +:readonly+
730
+
731
+ If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
732
+
733
+ h6. +:select+
734
+
735
+ The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
736
+
737
+ TIP: If you set the +:select+ option on a +belongs_to+ association, you should also set the +foreign_key+ option to guarantee the correct results.
738
+
739
+ h6. +:validate+
740
+
741
+ If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
742
+
743
+ h5. How To Know Whether There's an Associated Object?
744
+
745
+ To know whether there's and associated object just check <tt><em>association</em>.nil?</tt>:
746
+
747
+ <ruby>
748
+ if @order.customer.nil?
749
+ @msg = "No customer found for this order"
750
+ end
751
+ </ruby>
752
+
753
+ h5. When are Objects Saved?
754
+
755
+ Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either.
756
+
757
+ h4. +has_one+ Association Reference
758
+
759
+ The +has_one+ association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use +belongs_to+ instead.
760
+
761
+ h5. Methods Added by +has_one+
762
+
763
+ When you declare a +has_one+ association, the declaring class automatically gains four methods related to the association:
764
+
765
+ * <tt><em>association</em>(force_reload = false)</tt>
766
+ * <tt><em>association</em>=(associate)</tt>
767
+ * <tt>build_<em>association</em>(attributes = {})</tt>
768
+ * <tt>create_<em>association</em>(attributes = {})</tt>
769
+
770
+ In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to +has_one+. For example, given the declaration:
771
+
772
+ <ruby>
773
+ class Supplier < ActiveRecord::Base
774
+ has_one :account
775
+ end
776
+ </ruby>
777
+
778
+ Each instance of the +Supplier+ model will have these methods:
779
+
780
+ <ruby>
781
+ account
782
+ account=
783
+ build_account
784
+ create_account
785
+ </ruby>
786
+
787
+ h6. <tt><em>association</em>(force_reload = false)</tt>
788
+
789
+ The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.
790
+
791
+ <ruby>
792
+ @account = @supplier.account
793
+ </ruby>
794
+
795
+ If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument.
796
+
797
+ h6. <tt><em>association</em>=(associate)</tt>
798
+
799
+ The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.
800
+
801
+ <ruby>
802
+ @supplier.account = @account
803
+ </ruby>
804
+
805
+ h6. <tt>build_<em>association</em>(attributes = {})</tt>
806
+
807
+ The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.
808
+
809
+ <ruby>
810
+ @account = @supplier.build_account(:terms => "Net 30")
811
+ </ruby>
812
+
813
+ h6. <tt>create_<em>association</em>(attributes = {})</tt>
814
+
815
+ The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
816
+
817
+ <ruby>
818
+ @account = @supplier.create_account(:terms => "Net 30")
819
+ </ruby>
820
+
821
+ h5. Options for +has_one+
822
+
823
+ In many situations, you can use the default behavior of +has_one+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_one+ association. For example, an association with several options might look like this:
824
+
825
+ <ruby>
826
+ class Supplier < ActiveRecord::Base
827
+ has_one :account, :class_name => "Billing", :dependent => :nullify
828
+ end
829
+ </ruby>
830
+
831
+ The +has_one+ association supports these options:
832
+
833
+ * +:as+
834
+ * +:autosave+
835
+ * +:class_name+
836
+ * +:conditions+
837
+ * +:dependent+
838
+ * +:foreign_key+
839
+ * +:include+
840
+ * +:order+
841
+ * +:primary_key+
842
+ * +:readonly+
843
+ * +:select+
844
+ * +:source+
845
+ * +:source_type+
846
+ * +:through+
847
+ * +:validate+
848
+
849
+ h6. +:as+
850
+
851
+ Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
852
+
853
+ h6. +:autosave+
854
+
855
+ If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
856
+
857
+ h6. +:class_name+
858
+
859
+ If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is +Billing+, you'd set things up this way:
860
+
861
+ <ruby>
862
+ class Supplier < ActiveRecord::Base
863
+ has_one :account, :class_name => "Billing"
864
+ end
865
+ </ruby>
866
+
867
+ h6. +:conditions+
868
+
869
+ The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
870
+
871
+ <ruby>
872
+ class Supplier < ActiveRecord::Base
873
+ has_one :account, :conditions => "confirmed = 1"
874
+ end
875
+ </ruby>
876
+
877
+ h6. +:dependent+
878
+
879
+ If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+.
880
+
881
+ h6. +:foreign_key+
882
+
883
+ By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
884
+
885
+ <ruby>
886
+ class Supplier < ActiveRecord::Base
887
+ has_one :account, :foreign_key => "supp_id"
888
+ end
889
+ </ruby>
890
+
891
+ TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
892
+
893
+ h6. +:include+
894
+
895
+ You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
896
+
897
+ <ruby>
898
+ class Supplier < ActiveRecord::Base
899
+ has_one :account
900
+ end
901
+
902
+ class Account < ActiveRecord::Base
903
+ belongs_to :supplier
904
+ belongs_to :representative
905
+ end
906
+
907
+ class Representative < ActiveRecord::Base
908
+ has_many :accounts
909
+ end
910
+ </ruby>
911
+
912
+ If you frequently retrieve representatives directly from suppliers (+@supplier.account.representative+), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
913
+
914
+ <ruby>
915
+ class Supplier < ActiveRecord::Base
916
+ has_one :account, :include => :representative
917
+ end
918
+
919
+ class Account < ActiveRecord::Base
920
+ belongs_to :supplier
921
+ belongs_to :representative
922
+ end
923
+
924
+ class Representative < ActiveRecord::Base
925
+ has_many :accounts
926
+ end
927
+ </ruby>
928
+
929
+ h6. +:order+
930
+
931
+ The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
932
+
933
+ h6. +:primary_key+
934
+
935
+ By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
936
+
937
+ h6. +:readonly+
938
+
939
+ If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
940
+
941
+ h6. +:select+
942
+
943
+ The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
944
+
945
+ h6. +:source+
946
+
947
+ The +:source+ option specifies the source association name for a +has_one :through+ association.
948
+
949
+ h6. +:source_type+
950
+
951
+ The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
952
+
953
+ h6. :through
954
+
955
+ The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#the-has-one-through-association">earlier in this guide</a>.
956
+
957
+ h6. +:validate+
958
+
959
+ If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
960
+
961
+ h5. How To Know Whether There's an Associated Object?
962
+
963
+ To know whether there's and associated object just check <tt><em>association</em>.nil?</tt>:
964
+
965
+ <ruby>
966
+ if @supplier.account.nil?
967
+ @msg = "No account found for this supplier"
968
+ end
969
+ </ruby>
970
+
971
+ h5. When are Objects Saved?
972
+
973
+ When you assign an object to a +has_one+ association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.
974
+
975
+ If either of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
976
+
977
+ If the parent object (the one declaring the +has_one+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved. They will automatically when the parent object is saved.
978
+
979
+ If you want to assign an object to a +has_one+ association without saving the object, use the <tt><em>association</em>.build</tt> method.
980
+
981
+ h4. +has_many+ Association Reference
982
+
983
+ The +has_many+ association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.
984
+
985
+ h5. Methods Added
986
+
987
+ When you declare a +has_many+ association, the declaring class automatically gains 13 methods related to the association:
988
+
989
+ * <tt><em>collection</em>(force_reload = false)</tt>
990
+ * <tt><em>collection</em><<(object, ...)</tt>
991
+ * <tt><em>collection</em>.delete(object, ...)</tt>
992
+ * <tt><em>collection</em>=objects</tt>
993
+ * <tt><em>collection_singular</em>_ids</tt>
994
+ * <tt><em>collection_singular</em>_ids=ids</tt>
995
+ * <tt><em>collection</em>.clear</tt>
996
+ * <tt><em>collection</em>.empty?</tt>
997
+ * <tt><em>collection</em>.size</tt>
998
+ * <tt><em>collection</em>.find(...)</tt>
999
+ * <tt><em>collection</em>.exist?(...)</tt>
1000
+ * <tt><em>collection</em>.build(attributes = {}, ...)</tt>
1001
+ * <tt><em>collection</em>.create(attributes = {})</tt>
1002
+
1003
+ In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration:
1004
+
1005
+ <ruby>
1006
+ class Customer < ActiveRecord::Base
1007
+ has_many :orders
1008
+ end
1009
+ </ruby>
1010
+
1011
+ Each instance of the customer model will have these methods:
1012
+
1013
+ <ruby>
1014
+ orders(force_reload = false)
1015
+ orders<<(object, ...)
1016
+ orders.delete(object, ...)
1017
+ orders=objects
1018
+ order_ids
1019
+ order_ids=ids
1020
+ orders.clear
1021
+ orders.empty?
1022
+ orders.size
1023
+ orders.find(...)
1024
+ orders.exist?(...)
1025
+ orders.build(attributes = {}, ...)
1026
+ orders.create(attributes = {})
1027
+ </ruby>
1028
+
1029
+ h6. <tt><em>collection</em>(force_reload = false)</tt>
1030
+
1031
+ The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
1032
+
1033
+ <ruby>
1034
+ @orders = @customer.orders
1035
+ </ruby>
1036
+
1037
+ h6. <tt><em>collection</em><<(object, ...)</tt>
1038
+
1039
+ The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
1040
+
1041
+ <ruby>
1042
+ @customer.orders << @order1
1043
+ </ruby>
1044
+
1045
+ h6. <tt><em>collection</em>.delete(object, ...)</tt>
1046
+
1047
+ The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by setting their foreign keys to +NULL+.
1048
+
1049
+ <ruby>
1050
+ @customer.orders.delete(@order1)
1051
+ </ruby>
1052
+
1053
+ WARNING: Objects will be in addition destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+.
1054
+
1055
+
1056
+ h6. <tt><em>collection</em>=objects</tt>
1057
+
1058
+ The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
1059
+
1060
+ h6. <tt><em>collection_singular</em>_ids</tt>
1061
+
1062
+ The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.
1063
+
1064
+ <ruby>
1065
+ @order_ids = @customer.order_ids
1066
+ </ruby>
1067
+
1068
+ h6. <tt><em>collection_singular</em>_ids=ids</tt>
1069
+
1070
+ The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
1071
+
1072
+ h6. <tt><em>collection</em>.clear</tt>
1073
+
1074
+ The <tt><em>collection</em>.clear</tt> method removes every object from the collection. This destroys the associated objects if they are associated with +:dependent => :destroy+, deletes them directly from the database if +:dependent => :delete_all+, and otherwise sets their foreign keys to +NULL+.
1075
+
1076
+ h6. <tt><em>collection</em>.empty?</tt>
1077
+
1078
+ The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.
1079
+
1080
+ <ruby>
1081
+ <% if @customer.orders.empty? %>
1082
+ No Orders Found
1083
+ <% end %>
1084
+ </ruby>
1085
+
1086
+ h6. <tt><em>collection</em>.size</tt>
1087
+
1088
+ The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.
1089
+
1090
+ <ruby>
1091
+ @order_count = @customer.orders.size
1092
+ </ruby>
1093
+
1094
+ h6. <tt><em>collection</em>.find(...)</tt>
1095
+
1096
+ The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
1097
+
1098
+ <ruby>
1099
+ @open_orders = @customer.orders.find(:all, :conditions => "open = 1")
1100
+ </ruby>
1101
+
1102
+ h6. <tt><em>collection</em>.exist?(...)</tt>
1103
+
1104
+ The <tt><em>collection</em>.exist?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
1105
+
1106
+ h6. <tt><em>collection</em>.build(attributes = {}, ...)</tt>
1107
+
1108
+ The <tt><em>collection</em>.build</tt> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
1109
+
1110
+ <ruby>
1111
+ @order = @customer.orders.build(:order_date => Time.now,
1112
+ :order_number => "A12345")
1113
+ </ruby>
1114
+
1115
+ h6. <tt><em>collection</em>.create(attributes = {})</tt>
1116
+
1117
+ The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object _will_ be saved (assuming that it passes any validations).
1118
+
1119
+ <ruby>
1120
+ @order = @customer.orders.create(:order_date => Time.now,
1121
+ :order_number => "A12345")
1122
+ </ruby>
1123
+
1124
+ h5. Options for +has_many+
1125
+
1126
+ In many situations, you can use the default behavior for +has_many+ without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_many+ association. For example, an association with several options might look like this:
1127
+
1128
+ <ruby>
1129
+ class Customer < ActiveRecord::Base
1130
+ has_many :orders, :dependent => :delete_all, :validate => :false
1131
+ end
1132
+ </ruby>
1133
+
1134
+ The +has_many+ association supports these options:
1135
+
1136
+ * +:as+
1137
+ * +:autosave+
1138
+ * +:class_name+
1139
+ * +:conditions+
1140
+ * +:counter_sql+
1141
+ * +:dependent+
1142
+ * +:extend+
1143
+ * +:finder_sql+
1144
+ * +:foreign_key+
1145
+ * +:group+
1146
+ * +:include+
1147
+ * +:limit+
1148
+ * +:offset+
1149
+ * +:order+
1150
+ * +:primary_key+
1151
+ * +:readonly+
1152
+ * +:select+
1153
+ * +:source+
1154
+ * +:source_type+
1155
+ * +:through+
1156
+ * +:uniq+
1157
+ * +:validate+
1158
+
1159
+ h6. +:as+
1160
+
1161
+ Setting the +:as+ option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>.
1162
+
1163
+ h6. +:autosave+
1164
+
1165
+ If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
1166
+
1167
+ h6. +:class_name+
1168
+
1169
+ If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is +Transaction+, you'd set things up this way:
1170
+
1171
+ <ruby>
1172
+ class Customer < ActiveRecord::Base
1173
+ has_many :orders, :class_name => "Transaction"
1174
+ end
1175
+ </ruby>
1176
+
1177
+ h6. +:conditions+
1178
+
1179
+ The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
1180
+
1181
+ <ruby>
1182
+ class Customer < ActiveRecord::Base
1183
+ has_many :confirmed_orders, :class_name => "Order",
1184
+ :conditions => "confirmed = 1"
1185
+ end
1186
+ </ruby>
1187
+
1188
+ You can also set conditions via a hash:
1189
+
1190
+ <ruby>
1191
+ class Customer < ActiveRecord::Base
1192
+ has_many :confirmed_orders, :class_name => "Order",
1193
+ :conditions => { :confirmed => true }
1194
+ end
1195
+ </ruby>
1196
+
1197
+ If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.
1198
+
1199
+ h6. +:counter_sql+
1200
+
1201
+ Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
1202
+
1203
+ NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
1204
+
1205
+ h6. +:dependent+
1206
+
1207
+ If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+.
1208
+
1209
+ NOTE: This option is ignored when you use the +:through+ option on the association.
1210
+
1211
+ h6. +:extend+
1212
+
1213
+ The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
1214
+
1215
+ h6. +:finder_sql+
1216
+
1217
+ Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
1218
+
1219
+ h6. +:foreign_key+
1220
+
1221
+ By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
1222
+
1223
+ <ruby>
1224
+ class Customer < ActiveRecord::Base
1225
+ has_many :orders, :foreign_key => "cust_id"
1226
+ end
1227
+ </ruby>
1228
+
1229
+ TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
1230
+
1231
+ h6. +:group+
1232
+
1233
+ The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
1234
+
1235
+ <ruby>
1236
+ class Customer < ActiveRecord::Base
1237
+ has_many :line_items, :through => :orders, :group => "orders.id"
1238
+ end
1239
+ </ruby>
1240
+
1241
+ h6. +:include+
1242
+
1243
+ You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
1244
+
1245
+ <ruby>
1246
+ class Customer < ActiveRecord::Base
1247
+ has_many :orders
1248
+ end
1249
+
1250
+ class Order < ActiveRecord::Base
1251
+ belongs_to :customer
1252
+ has_many :line_items
1253
+ end
1254
+
1255
+ class LineItem < ActiveRecord::Base
1256
+ belongs_to :order
1257
+ end
1258
+ </ruby>
1259
+
1260
+ If you frequently retrieve line items directly from customers (+@customer.orders.line_items+), then you can make your code somewhat more efficient by including line items in the association from customers to orders:
1261
+
1262
+ <ruby>
1263
+ class Customer < ActiveRecord::Base
1264
+ has_many :orders, :include => :line_items
1265
+ end
1266
+
1267
+ class Order < ActiveRecord::Base
1268
+ belongs_to :customer
1269
+ has_many :line_items
1270
+ end
1271
+
1272
+ class LineItem < ActiveRecord::Base
1273
+ belongs_to :order
1274
+ end
1275
+ </ruby>
1276
+
1277
+ h6. +:limit+
1278
+
1279
+ The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
1280
+
1281
+ <ruby>
1282
+ class Customer < ActiveRecord::Base
1283
+ has_many :recent_orders, :class_name => "Order",
1284
+ :order => "order_date DESC", :limit => 100
1285
+ end
1286
+ </ruby>
1287
+
1288
+ h6. +:offset+
1289
+
1290
+ The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records.
1291
+
1292
+ h6. +:order+
1293
+
1294
+ The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
1295
+
1296
+ <ruby>
1297
+ class Customer < ActiveRecord::Base
1298
+ has_many :orders, :order => "date_confirmed DESC"
1299
+ end
1300
+ </ruby>
1301
+
1302
+ h6. +:primary_key+
1303
+
1304
+ By convention, Rails guesses that the column used to hold the primary key of the association is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
1305
+
1306
+ h6. +:readonly+
1307
+
1308
+ If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
1309
+
1310
+ h6. +:select+
1311
+
1312
+ The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
1313
+
1314
+ WARNING: If you specify your own +:select+, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.
1315
+
1316
+ h6. +:source+
1317
+
1318
+ The +:source+ option specifies the source association name for a +has_many :through+ association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
1319
+
1320
+ h6. +:source_type+
1321
+
1322
+ The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
1323
+
1324
+ h6. +:through+
1325
+
1326
+ The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed <a href="#the-has-many-through-association">earlier in this guide</a>.
1327
+
1328
+ h6. +:uniq+
1329
+
1330
+ Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
1331
+
1332
+ h6. +:validate+
1333
+
1334
+ If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
1335
+
1336
+ h5. When are Objects Saved?
1337
+
1338
+ When you assign an object to a +has_many+ association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.
1339
+
1340
+ If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1341
+
1342
+ If the parent object (the one declaring the +has_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
1343
+
1344
+ If you want to assign an object to a +has_many+ association without saving the object, use the <tt><em>collection</em>.build</tt> method.
1345
+
1346
+ h4. +has_and_belongs_to_many+ Association Reference
1347
+
1348
+ The +has_and_belongs_to_many+ association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.
1349
+
1350
+ h5. Methods Added
1351
+
1352
+ When you declare a +has_and_belongs_to_many+ association, the declaring class automatically gains 13 methods related to the association:
1353
+
1354
+ * <tt><em>collection</em>(force_reload = false)</tt>
1355
+ * <tt><em>collection</em><<(object, ...)</tt>
1356
+ * <tt><em>collection</em>.delete(object, ...)</tt>
1357
+ * <tt><em>collection</em>=objects</tt>
1358
+ * <tt><em>collection_singular</em>_ids</tt>
1359
+ * <tt><em>collection_singular</em>_ids=ids</tt>
1360
+ * <tt><em>collection</em>.clear</tt>
1361
+ * <tt><em>collection</em>.empty?</tt>
1362
+ * <tt><em>collection</em>.size</tt>
1363
+ * <tt><em>collection</em>.find(...)</tt>
1364
+ * <tt><em>collection</em>.exist?(...)</tt>
1365
+ * <tt><em>collection</em>.build(attributes = {})</tt>
1366
+ * <tt><em>collection</em>.create(attributes = {})</tt>
1367
+
1368
+ In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_and_belongs_to_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration:
1369
+
1370
+ <ruby>
1371
+ class Part < ActiveRecord::Base
1372
+ has_and_belongs_to_many :assemblies
1373
+ end
1374
+ </ruby>
1375
+
1376
+ Each instance of the part model will have these methods:
1377
+
1378
+ <ruby>
1379
+ assemblies(force_reload = false)
1380
+ assemblies<<(object, ...)
1381
+ assemblies.delete(object, ...)
1382
+ assemblies=objects
1383
+ assembly_ids
1384
+ assembly_ids=ids
1385
+ assemblies.clear
1386
+ assemblies.empty?
1387
+ assemblies.size
1388
+ assemblies.find(...)
1389
+ assemblies.exist?(...)
1390
+ assemblies.build(attributes = {}, ...)
1391
+ assemblies.create(attributes = {})
1392
+ </ruby>
1393
+
1394
+ h6. Additional Column Methods
1395
+
1396
+ If the join table for a +has_and_belongs_to_many+ association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.
1397
+
1398
+ WARNING: The use of extra attributes on the join table in a +has_and_belongs_to_many+ association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a +has_many :through+ association instead of +has_and_belongs_to_many+.
1399
+
1400
+
1401
+ h6. <tt><em>collection</em>(force_reload = false)</tt>
1402
+
1403
+ The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
1404
+
1405
+ <ruby>
1406
+ @assemblies = @part.assemblies
1407
+ </ruby>
1408
+
1409
+ h6. <tt><em>collection</em><<(object, ...)</tt>
1410
+
1411
+ The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by creating records in the join table.
1412
+
1413
+ <ruby>
1414
+ @part.assemblies << @assembly1
1415
+ </ruby>
1416
+
1417
+ NOTE: This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>.
1418
+
1419
+ h6. <tt><em>collection</em>.delete(object, ...)</tt>
1420
+
1421
+ The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
1422
+
1423
+ <ruby>
1424
+ @part.assemblies.delete(@assembly1)
1425
+ </ruby>
1426
+
1427
+ h6. <tt><em>collection</em>=objects</tt>
1428
+
1429
+ The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
1430
+
1431
+ h6. <tt><em>collection_singular</em>_ids</tt>
1432
+
1433
+ The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.
1434
+
1435
+ <ruby>
1436
+ @assembly_ids = @part.assembly_ids
1437
+ </ruby>
1438
+
1439
+ h6. <tt><em>collection_singular</em>_ids=ids</tt>
1440
+
1441
+ The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
1442
+
1443
+ h6. <tt><em>collection</em>.clear</tt>
1444
+
1445
+ The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.
1446
+
1447
+ h6. <tt><em>collection</em>.empty?</tt>
1448
+
1449
+ The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.
1450
+
1451
+ <ruby>
1452
+ <% if @part.assemblies.empty? %>
1453
+ This part is not used in any assemblies
1454
+ <% end %>
1455
+ </ruby>
1456
+
1457
+ h6. <tt><em>collection</em>.size</tt>
1458
+
1459
+ The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.
1460
+
1461
+ <ruby>
1462
+ @assembly_count = @part.assemblies.size
1463
+ </ruby>
1464
+
1465
+ h6. <tt><em>collection</em>.find(...)</tt>
1466
+
1467
+ The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.
1468
+
1469
+ <ruby>
1470
+ @new_assemblies = @part.assemblies.find(:all,
1471
+ :conditions => ["created_at > ?", 2.days.ago])
1472
+ </ruby>
1473
+
1474
+ h6. <tt><em>collection</em>.exist?(...)</tt>
1475
+
1476
+ The <tt><em>collection</em>.exist?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
1477
+
1478
+ h6. <tt><em>collection</em>.build(attributes = {})</tt>
1479
+
1480
+ The <tt><em>collection</em>.build</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will _not_ yet be saved.
1481
+
1482
+ <ruby>
1483
+ @assembly = @part.assemblies.build(
1484
+ {:assembly_name => "Transmission housing"})
1485
+ </ruby>
1486
+
1487
+ h6. <tt><em>collection</em>.create(attributes = {})</tt>
1488
+
1489
+ The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and the associated object _will_ be saved (assuming that it passes any validations).
1490
+
1491
+ <ruby>
1492
+ @assembly = @part.assemblies.create(
1493
+ {:assembly_name => "Transmission housing"})
1494
+ </ruby>
1495
+
1496
+ h5. Options for +has_and_belongs_to_many+
1497
+
1498
+ In many situations, you can use the default behavior for +has_and_belongs_to_many+ without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_and_belongs_to_many+ association. For example, an association with several options might look like this:
1499
+
1500
+ <ruby>
1501
+ class Parts < ActiveRecord::Base
1502
+ has_and_belongs_to_many :assemblies, :uniq => true,
1503
+ :read_only => true
1504
+ end
1505
+ </ruby>
1506
+
1507
+ The +has_and_belongs_to_many+ association supports these options:
1508
+
1509
+ * +:association_foreign_key+
1510
+ * +:autosave+
1511
+ * +:class_name+
1512
+ * +:conditions+
1513
+ * +:counter_sql+
1514
+ * +:delete_sql+
1515
+ * +:extend+
1516
+ * +:finder_sql+
1517
+ * +:foreign_key+
1518
+ * +:group+
1519
+ * +:include+
1520
+ * +:insert_sql+
1521
+ * +:join_table+
1522
+ * +:limit+
1523
+ * +:offset+
1524
+ * +:order+
1525
+ * +:readonly+
1526
+ * +:select+
1527
+ * +:uniq+
1528
+ * +:validate+
1529
+
1530
+ h6. +:association_foreign_key+
1531
+
1532
+ By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly:
1533
+
1534
+ TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when setting up a many-to-many self-join. For example:
1535
+
1536
+ <ruby>
1537
+ class User < ActiveRecord::Base
1538
+ has_and_belongs_to_many :friends, :class_name => "User",
1539
+ :foreign_key => "this_user_id",
1540
+ :association_foreign_key => "other_user_id"
1541
+ end
1542
+ </ruby>
1543
+
1544
+ h6. +:autosave+
1545
+
1546
+ If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
1547
+
1548
+ h6. +:class_name+
1549
+
1550
+ If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is +Gadget+, you'd set things up this way:
1551
+
1552
+ <ruby>
1553
+ class Parts < ActiveRecord::Base
1554
+ has_and_belongs_to_many :assemblies, :class_name => "Gadget"
1555
+ end
1556
+ </ruby>
1557
+
1558
+ h6. +:conditions+
1559
+
1560
+ The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
1561
+
1562
+ <ruby>
1563
+ class Parts < ActiveRecord::Base
1564
+ has_and_belongs_to_many :assemblies,
1565
+ :conditions => "factory = 'Seattle'"
1566
+ end
1567
+ </ruby>
1568
+
1569
+ You can also set conditions via a hash:
1570
+
1571
+ <ruby>
1572
+ class Parts < ActiveRecord::Base
1573
+ has_and_belongs_to_many :assemblies,
1574
+ :conditions => { :factory => 'Seattle' }
1575
+ end
1576
+ </ruby>
1577
+
1578
+ If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the +factory+ column has the value "Seattle".
1579
+
1580
+ h6. +:counter_sql+
1581
+
1582
+ Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
1583
+
1584
+ NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
1585
+
1586
+ h6. +:delete_sql+
1587
+
1588
+ Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the +:delete_sql+ option, you can specify a complete SQL statement to delete them yourself.
1589
+
1590
+ h6. +:extend+
1591
+
1592
+ The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
1593
+
1594
+ h6. +:finder_sql+
1595
+
1596
+ Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
1597
+
1598
+ h6. +:foreign_key+
1599
+
1600
+ By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
1601
+
1602
+ <ruby>
1603
+ class User < ActiveRecord::Base
1604
+ has_and_belongs_to_many :friends, :class_name => "User",
1605
+ :foreign_key => "this_user_id",
1606
+ :association_foreign_key => "other_user_id"
1607
+ end
1608
+ </ruby>
1609
+
1610
+ h6. +:group+
1611
+
1612
+ The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
1613
+
1614
+ <ruby>
1615
+ class Parts < ActiveRecord::Base
1616
+ has_and_belongs_to_many :assemblies, :group => "factory"
1617
+ end
1618
+ </ruby>
1619
+
1620
+ h6. +:include+
1621
+
1622
+ You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used.
1623
+
1624
+ h6. +:insert_sql+
1625
+
1626
+ Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself.
1627
+
1628
+ h6. +:join_table+
1629
+
1630
+ If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default.
1631
+
1632
+ h6. +:limit+
1633
+
1634
+ The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
1635
+
1636
+ <ruby>
1637
+ class Parts < ActiveRecord::Base
1638
+ has_and_belongs_to_many :assemblies, :order => "created_at DESC",
1639
+ :limit => 50
1640
+ end
1641
+ </ruby>
1642
+
1643
+ h6. +:offset+
1644
+
1645
+ The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records.
1646
+
1647
+ h6. +:order+
1648
+
1649
+ The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
1650
+
1651
+ <ruby>
1652
+ class Parts < ActiveRecord::Base
1653
+ has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
1654
+ end
1655
+ </ruby>
1656
+
1657
+ h6. +:readonly+
1658
+
1659
+ If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
1660
+
1661
+ h6. +:select+
1662
+
1663
+ The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
1664
+
1665
+ h6. +:uniq+
1666
+
1667
+ Specify the +:uniq => true+ option to remove duplicates from the collection.
1668
+
1669
+ h6. +:validate+
1670
+
1671
+ If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
1672
+
1673
+ h5. When are Objects Saved?
1674
+
1675
+ When you assign an object to a +has_and_belongs_to_many+ association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.
1676
+
1677
+ If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1678
+
1679
+ If the parent object (the one declaring the +has_and_belongs_to_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
1680
+
1681
+ If you want to assign an object to a +has_and_belongs_to_many+ association without saving the object, use the <tt><em>collection</em>.build</tt> method.
1682
+
1683
+ h4. Association Callbacks
1684
+
1685
+ Normal callbacks hook into the lifecycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a +:before_save+ callback to cause something to happen just before an object is saved.
1686
+
1687
+ Association callbacks are similar to normal callbacks, but they are triggered by events in the lifecycle of a collection. There are four available association callbacks:
1688
+
1689
+ * +before_add+
1690
+ * +after_add+
1691
+ * +before_remove+
1692
+ * +after_remove+
1693
+
1694
+ You define association callbacks by adding options to the association declaration. For example:
1695
+
1696
+ <ruby>
1697
+ class Customer < ActiveRecord::Base
1698
+ has_many :orders, :before_add => :check_credit_limit
1699
+
1700
+ def check_credit_limit(order)
1701
+ ...
1702
+ end
1703
+ end
1704
+ </ruby>
1705
+
1706
+ Rails passes the object being added or removed to the callback.
1707
+
1708
+ You can stack callbacks on a single event by passing them as an array:
1709
+
1710
+ <ruby>
1711
+ class Customer < ActiveRecord::Base
1712
+ has_many :orders,
1713
+ :before_add => [:check_credit_limit, :calculate_shipping_charges]
1714
+
1715
+ def check_credit_limit(order)
1716
+ ...
1717
+ end
1718
+
1719
+ def calculate_shipping_charges(order)
1720
+ ...
1721
+ end
1722
+ end
1723
+ </ruby>
1724
+
1725
+ If a +before_add+ callback throws an exception, the object does not get added to the collection. Similarly, if a +before_remove+ callback throws an exception, the object does not get removed from the collection.
1726
+
1727
+ h4. Association Extensions
1728
+
1729
+ You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:
1730
+
1731
+ <ruby>
1732
+ class Customer < ActiveRecord::Base
1733
+ has_many :orders do
1734
+ def find_by_order_prefix(order_number)
1735
+ find_by_region_id(order_number[0..2])
1736
+ end
1737
+ end
1738
+ end
1739
+ </ruby>
1740
+
1741
+ If you have an extension that should be shared by many associations, you can use a named extension module. For example:
1742
+
1743
+ <ruby>
1744
+ module FindRecentExtension
1745
+ def find_recent
1746
+ find(:all, :conditions => ["created_at > ?", 5.days.ago])
1747
+ end
1748
+ end
1749
+
1750
+ class Customer < ActiveRecord::Base
1751
+ has_many :orders, :extend => FindRecentExtension
1752
+ end
1753
+
1754
+ class Supplier < ActiveRecord::Base
1755
+ has_many :deliveries, :extend => FindRecentExtension
1756
+ end
1757
+ </ruby>
1758
+
1759
+ To include more than one extension module in a single association, specify an array of modules:
1760
+
1761
+ <ruby>
1762
+ class Customer < ActiveRecord::Base
1763
+ has_many :orders,
1764
+ :extend => [FindRecentExtension, FindActiveExtension]
1765
+ end
1766
+ </ruby>
1767
+
1768
+ Extensions can refer to the internals of the association proxy using these three accessors:
1769
+
1770
+ * +proxy_owner+ returns the object that the association is a part of.
1771
+ * +proxy_reflection+ returns the reflection object that describes the association.
1772
+ * +proxy_target+ returns the associated object for +belongs_to+ or +has_one+, or the collection of associated objects for +has_many+ or +has_and_belongs_to_many+.
1773
+
1774
+ h3. Changelog
1775
+
1776
+ "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11
1777
+
1778
+ * February 1, 2009: Added +:autosave+ option "Mike Gunderloy":credits.html#mgunderloy
1779
+ * September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by "Mike Gunderloy":credits.html#mgunderloy . First release version.
1780
+ * September 22, 2008: Added diagrams, misc. cleanup by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
1781
+ * September 14, 2008: initial version by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)