railties 3.0.0.beta

Sign up to get free protection for your applications and to get access to all the features.
Files changed (334) hide show
  1. data/CHANGELOG +2201 -0
  2. data/README +286 -0
  3. data/bin/rails +11 -0
  4. data/builtin/rails_info/rails/info.rb +147 -0
  5. data/builtin/rails_info/rails/info_controller.rb +15 -0
  6. data/builtin/rails_info/rails/info_helper.rb +2 -0
  7. data/builtin/routes.rb +3 -0
  8. data/guides/files/javascripts/code_highlighter.js +188 -0
  9. data/guides/files/javascripts/guides.js +7 -0
  10. data/guides/files/javascripts/highlighters.js +90 -0
  11. data/guides/files/stylesheets/main.css +441 -0
  12. data/guides/files/stylesheets/print.css +52 -0
  13. data/guides/files/stylesheets/reset.css +43 -0
  14. data/guides/files/stylesheets/style.css +13 -0
  15. data/guides/files/stylesheets/syntax.css +31 -0
  16. data/guides/images/belongs_to.png +0 -0
  17. data/guides/images/book_icon.gif +0 -0
  18. data/guides/images/bullet.gif +0 -0
  19. data/guides/images/chapters_icon.gif +0 -0
  20. data/guides/images/check_bullet.gif +0 -0
  21. data/guides/images/credits_pic_blank.gif +0 -0
  22. data/guides/images/csrf.png +0 -0
  23. data/guides/images/customized_error_messages.png +0 -0
  24. data/guides/images/error_messages.png +0 -0
  25. data/guides/images/feature_tile.gif +0 -0
  26. data/guides/images/footer_tile.gif +0 -0
  27. data/guides/images/fxn.png +0 -0
  28. data/guides/images/grey_bullet.gif +0 -0
  29. data/guides/images/habtm.png +0 -0
  30. data/guides/images/has_many.png +0 -0
  31. data/guides/images/has_many_through.png +0 -0
  32. data/guides/images/has_one.png +0 -0
  33. data/guides/images/has_one_through.png +0 -0
  34. data/guides/images/header_backdrop.png +0 -0
  35. data/guides/images/header_tile.gif +0 -0
  36. data/guides/images/i18n/demo_localized_pirate.png +0 -0
  37. data/guides/images/i18n/demo_translated_en.png +0 -0
  38. data/guides/images/i18n/demo_translated_pirate.png +0 -0
  39. data/guides/images/i18n/demo_translation_missing.png +0 -0
  40. data/guides/images/i18n/demo_untranslated.png +0 -0
  41. data/guides/images/icons/README +5 -0
  42. data/guides/images/icons/callouts/1.png +0 -0
  43. data/guides/images/icons/callouts/10.png +0 -0
  44. data/guides/images/icons/callouts/11.png +0 -0
  45. data/guides/images/icons/callouts/12.png +0 -0
  46. data/guides/images/icons/callouts/13.png +0 -0
  47. data/guides/images/icons/callouts/14.png +0 -0
  48. data/guides/images/icons/callouts/15.png +0 -0
  49. data/guides/images/icons/callouts/2.png +0 -0
  50. data/guides/images/icons/callouts/3.png +0 -0
  51. data/guides/images/icons/callouts/4.png +0 -0
  52. data/guides/images/icons/callouts/5.png +0 -0
  53. data/guides/images/icons/callouts/6.png +0 -0
  54. data/guides/images/icons/callouts/7.png +0 -0
  55. data/guides/images/icons/callouts/8.png +0 -0
  56. data/guides/images/icons/callouts/9.png +0 -0
  57. data/guides/images/icons/caution.png +0 -0
  58. data/guides/images/icons/example.png +0 -0
  59. data/guides/images/icons/home.png +0 -0
  60. data/guides/images/icons/important.png +0 -0
  61. data/guides/images/icons/next.png +0 -0
  62. data/guides/images/icons/note.png +0 -0
  63. data/guides/images/icons/prev.png +0 -0
  64. data/guides/images/icons/tip.png +0 -0
  65. data/guides/images/icons/up.png +0 -0
  66. data/guides/images/icons/warning.png +0 -0
  67. data/guides/images/nav_arrow.gif +0 -0
  68. data/guides/images/polymorphic.png +0 -0
  69. data/guides/images/posts_index.png +0 -0
  70. data/guides/images/rails_guides_logo.gif +0 -0
  71. data/guides/images/rails_logo_remix.gif +0 -0
  72. data/guides/images/rails_welcome.png +0 -0
  73. data/guides/images/session_fixation.png +0 -0
  74. data/guides/images/tab_grey.gif +0 -0
  75. data/guides/images/tab_info.gif +0 -0
  76. data/guides/images/tab_note.gif +0 -0
  77. data/guides/images/tab_red.gif +0 -0
  78. data/guides/images/tab_yellow.gif +0 -0
  79. data/guides/images/tab_yellow.png +0 -0
  80. data/guides/images/validation_error_messages.png +0 -0
  81. data/guides/rails_guides.rb +44 -0
  82. data/guides/rails_guides/generator.rb +178 -0
  83. data/guides/rails_guides/helpers.rb +34 -0
  84. data/guides/rails_guides/indexer.rb +55 -0
  85. data/guides/rails_guides/levenshtein.rb +31 -0
  86. data/guides/rails_guides/textile_extensions.rb +41 -0
  87. data/guides/source/2_2_release_notes.textile +422 -0
  88. data/guides/source/2_3_release_notes.textile +610 -0
  89. data/guides/source/3_0_release_notes.textile +560 -0
  90. data/guides/source/action_controller_overview.textile +783 -0
  91. data/guides/source/action_mailer_basics.textile +437 -0
  92. data/guides/source/action_view_overview.textile +1481 -0
  93. data/guides/source/active_record_basics.textile +204 -0
  94. data/guides/source/active_record_querying.textile +961 -0
  95. data/guides/source/active_support_core_extensions.textile +1835 -0
  96. data/guides/source/activerecord_validations_callbacks.textile +1127 -0
  97. data/guides/source/ajax_on_rails.textile +342 -0
  98. data/guides/source/association_basics.textile +1816 -0
  99. data/guides/source/caching_with_rails.textile +390 -0
  100. data/guides/source/command_line.textile +589 -0
  101. data/guides/source/configuring.textile +290 -0
  102. data/guides/source/contribute.textile +71 -0
  103. data/guides/source/contributing_to_rails.textile +272 -0
  104. data/guides/source/credits.textile.erb +52 -0
  105. data/guides/source/debugging_rails_applications.textile +709 -0
  106. data/guides/source/form_helpers.textile +768 -0
  107. data/guides/source/generators.textile +378 -0
  108. data/guides/source/getting_started.textile +1310 -0
  109. data/guides/source/i18n.textile +879 -0
  110. data/guides/source/index.textile.erb +124 -0
  111. data/guides/source/layout.html.erb +103 -0
  112. data/guides/source/layouts_and_rendering.textile +979 -0
  113. data/guides/source/migrations.textile +591 -0
  114. data/guides/source/nested_model_forms.textile +222 -0
  115. data/guides/source/performance_testing.textile +531 -0
  116. data/guides/source/plugins.textile +1512 -0
  117. data/guides/source/rails_application_templates.textile +238 -0
  118. data/guides/source/rails_on_rack.textile +306 -0
  119. data/guides/source/routing.textile +903 -0
  120. data/guides/source/security.textile +984 -0
  121. data/guides/source/testing.textile +946 -0
  122. data/lib/generators/erb.rb +8 -0
  123. data/lib/generators/erb/controller/controller_generator.rb +21 -0
  124. data/lib/generators/erb/controller/templates/view.html.erb +2 -0
  125. data/lib/generators/erb/mailer/mailer_generator.rb +20 -0
  126. data/lib/generators/erb/mailer/templates/view.text.erb +3 -0
  127. data/lib/generators/erb/scaffold/scaffold_generator.rb +53 -0
  128. data/lib/generators/erb/scaffold/templates/_form.html.erb +13 -0
  129. data/lib/generators/erb/scaffold/templates/edit.html.erb +6 -0
  130. data/lib/generators/erb/scaffold/templates/index.html.erb +27 -0
  131. data/lib/generators/erb/scaffold/templates/layout.html.erb +16 -0
  132. data/lib/generators/erb/scaffold/templates/new.html.erb +5 -0
  133. data/lib/generators/erb/scaffold/templates/show.html.erb +10 -0
  134. data/lib/generators/rails/app/USAGE +9 -0
  135. data/lib/generators/rails/app/app_generator.rb +262 -0
  136. data/lib/generators/rails/app/templates/Gemfile +34 -0
  137. data/lib/generators/rails/app/templates/README +243 -0
  138. data/lib/generators/rails/app/templates/Rakefile +10 -0
  139. data/lib/generators/rails/app/templates/app/controllers/application_controller.rb +3 -0
  140. data/lib/generators/rails/app/templates/app/helpers/application_helper.rb +2 -0
  141. data/lib/generators/rails/app/templates/app/models/.empty_directory +0 -0
  142. data/lib/generators/rails/app/templates/app/views/layouts/.empty_directory +0 -0
  143. data/lib/generators/rails/app/templates/config.ru +4 -0
  144. data/lib/generators/rails/app/templates/config/application.rb +51 -0
  145. data/lib/generators/rails/app/templates/config/boot.rb +17 -0
  146. data/lib/generators/rails/app/templates/config/databases/frontbase.yml +28 -0
  147. data/lib/generators/rails/app/templates/config/databases/ibm_db.yml +71 -0
  148. data/lib/generators/rails/app/templates/config/databases/mysql.yml +60 -0
  149. data/lib/generators/rails/app/templates/config/databases/oracle.yml +39 -0
  150. data/lib/generators/rails/app/templates/config/databases/postgresql.yml +51 -0
  151. data/lib/generators/rails/app/templates/config/databases/sqlite3.yml +22 -0
  152. data/lib/generators/rails/app/templates/config/environment.rb +5 -0
  153. data/lib/generators/rails/app/templates/config/environments/development.rb.tt +19 -0
  154. data/lib/generators/rails/app/templates/config/environments/production.rb.tt +33 -0
  155. data/lib/generators/rails/app/templates/config/environments/test.rb.tt +29 -0
  156. data/lib/generators/rails/app/templates/config/initializers/backtrace_silencers.rb +7 -0
  157. data/lib/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt +7 -0
  158. data/lib/generators/rails/app/templates/config/initializers/inflections.rb +10 -0
  159. data/lib/generators/rails/app/templates/config/initializers/mime_types.rb +5 -0
  160. data/lib/generators/rails/app/templates/config/initializers/session_store.rb.tt +15 -0
  161. data/lib/generators/rails/app/templates/config/locales/en.yml +5 -0
  162. data/lib/generators/rails/app/templates/config/routes.rb +58 -0
  163. data/lib/generators/rails/app/templates/db/seeds.rb +7 -0
  164. data/lib/generators/rails/app/templates/doc/README_FOR_APP +2 -0
  165. data/lib/generators/rails/app/templates/gitignore +4 -0
  166. data/lib/generators/rails/app/templates/public/404.html +26 -0
  167. data/lib/generators/rails/app/templates/public/422.html +26 -0
  168. data/lib/generators/rails/app/templates/public/500.html +26 -0
  169. data/lib/generators/rails/app/templates/public/favicon.ico +0 -0
  170. data/lib/generators/rails/app/templates/public/images/rails.png +0 -0
  171. data/lib/generators/rails/app/templates/public/index.html +278 -0
  172. data/lib/generators/rails/app/templates/public/javascripts/application.js +2 -0
  173. data/lib/generators/rails/app/templates/public/javascripts/controls.js +963 -0
  174. data/lib/generators/rails/app/templates/public/javascripts/dragdrop.js +973 -0
  175. data/lib/generators/rails/app/templates/public/javascripts/effects.js +1128 -0
  176. data/lib/generators/rails/app/templates/public/javascripts/prototype.js +4320 -0
  177. data/lib/generators/rails/app/templates/public/javascripts/rails.js +110 -0
  178. data/lib/generators/rails/app/templates/public/robots.txt +5 -0
  179. data/lib/generators/rails/app/templates/public/stylesheets/.empty_directory +0 -0
  180. data/lib/generators/rails/app/templates/script/rails +9 -0
  181. data/lib/generators/rails/app/templates/test/fixtures/.empty_directory +0 -0
  182. data/lib/generators/rails/app/templates/test/functional/.empty_directory +0 -0
  183. data/lib/generators/rails/app/templates/test/integration/.empty_directory +0 -0
  184. data/lib/generators/rails/app/templates/test/performance/browsing_test.rb +9 -0
  185. data/lib/generators/rails/app/templates/test/test_helper.rb +13 -0
  186. data/lib/generators/rails/app/templates/test/unit/.empty_directory +0 -0
  187. data/lib/generators/rails/controller/USAGE +18 -0
  188. data/lib/generators/rails/controller/controller_generator.rb +14 -0
  189. data/lib/generators/rails/controller/templates/controller.rb +7 -0
  190. data/lib/generators/rails/generator/USAGE +11 -0
  191. data/lib/generators/rails/generator/generator_generator.rb +25 -0
  192. data/lib/generators/rails/generator/templates/%file_name%_generator.rb.tt +5 -0
  193. data/lib/generators/rails/generator/templates/USAGE.tt +8 -0
  194. data/lib/generators/rails/generator/templates/templates/.empty_directory +0 -0
  195. data/lib/generators/rails/helper/USAGE +17 -0
  196. data/lib/generators/rails/helper/helper_generator.rb +13 -0
  197. data/lib/generators/rails/helper/templates/helper.rb +2 -0
  198. data/lib/generators/rails/integration_test/USAGE +10 -0
  199. data/lib/generators/rails/integration_test/integration_test_generator.rb +7 -0
  200. data/lib/generators/rails/mailer/USAGE +15 -0
  201. data/lib/generators/rails/mailer/mailer_generator.rb +14 -0
  202. data/lib/generators/rails/mailer/templates/mailer.rb +16 -0
  203. data/lib/generators/rails/metal/USAGE +8 -0
  204. data/lib/generators/rails/metal/metal_generator.rb +11 -0
  205. data/lib/generators/rails/metal/templates/metal.rb +12 -0
  206. data/lib/generators/rails/migration/USAGE +29 -0
  207. data/lib/generators/rails/migration/migration_generator.rb +8 -0
  208. data/lib/generators/rails/model/USAGE +30 -0
  209. data/lib/generators/rails/model/model_generator.rb +8 -0
  210. data/lib/generators/rails/model_subclass/model_subclass_generator.rb +12 -0
  211. data/lib/generators/rails/observer/USAGE +12 -0
  212. data/lib/generators/rails/observer/observer_generator.rb +7 -0
  213. data/lib/generators/rails/performance_test/USAGE +10 -0
  214. data/lib/generators/rails/performance_test/performance_test_generator.rb +7 -0
  215. data/lib/generators/rails/plugin/USAGE +13 -0
  216. data/lib/generators/rails/plugin/plugin_generator.rb +47 -0
  217. data/lib/generators/rails/plugin/templates/MIT-LICENSE.tt +20 -0
  218. data/lib/generators/rails/plugin/templates/README.tt +13 -0
  219. data/lib/generators/rails/plugin/templates/Rakefile.tt +10 -0
  220. data/lib/generators/rails/plugin/templates/init.rb +1 -0
  221. data/lib/generators/rails/plugin/templates/install.rb +1 -0
  222. data/lib/generators/rails/plugin/templates/lib/%file_name%.rb.tt +1 -0
  223. data/lib/generators/rails/plugin/templates/lib/tasks/%file_name%_tasks.rake.tt +4 -0
  224. data/lib/generators/rails/plugin/templates/uninstall.rb +1 -0
  225. data/lib/generators/rails/resource/USAGE +23 -0
  226. data/lib/generators/rails/resource/resource_generator.rb +34 -0
  227. data/lib/generators/rails/scaffold/USAGE +29 -0
  228. data/lib/generators/rails/scaffold/scaffold_generator.rb +13 -0
  229. data/lib/generators/rails/scaffold_controller/USAGE +20 -0
  230. data/lib/generators/rails/scaffold_controller/scaffold_controller_generator.rb +27 -0
  231. data/lib/generators/rails/scaffold_controller/templates/controller.rb +85 -0
  232. data/lib/generators/rails/session_migration/USAGE +8 -0
  233. data/lib/generators/rails/session_migration/session_migration_generator.rb +8 -0
  234. data/lib/generators/rails/stylesheets/USAGE +5 -0
  235. data/lib/generators/rails/stylesheets/stylesheets_generator.rb +9 -0
  236. data/lib/generators/rails/stylesheets/templates/scaffold.css +61 -0
  237. data/lib/generators/test_unit.rb +8 -0
  238. data/lib/generators/test_unit/controller/controller_generator.rb +14 -0
  239. data/lib/generators/test_unit/controller/templates/functional_test.rb +8 -0
  240. data/lib/generators/test_unit/helper/helper_generator.rb +13 -0
  241. data/lib/generators/test_unit/helper/templates/helper_test.rb +4 -0
  242. data/lib/generators/test_unit/integration/integration_generator.rb +13 -0
  243. data/lib/generators/test_unit/integration/templates/integration_test.rb +10 -0
  244. data/lib/generators/test_unit/mailer/mailer_generator.rb +21 -0
  245. data/lib/generators/test_unit/mailer/templates/fixture +3 -0
  246. data/lib/generators/test_unit/mailer/templates/functional_test.rb +22 -0
  247. data/lib/generators/test_unit/model/model_generator.rb +24 -0
  248. data/lib/generators/test_unit/model/templates/fixtures.yml +23 -0
  249. data/lib/generators/test_unit/model/templates/unit_test.rb +8 -0
  250. data/lib/generators/test_unit/observer/observer_generator.rb +13 -0
  251. data/lib/generators/test_unit/observer/templates/unit_test.rb +8 -0
  252. data/lib/generators/test_unit/performance/performance_generator.rb +13 -0
  253. data/lib/generators/test_unit/performance/templates/performance_test.rb +9 -0
  254. data/lib/generators/test_unit/plugin/plugin_generator.rb +13 -0
  255. data/lib/generators/test_unit/plugin/templates/%file_name%_test.rb.tt +8 -0
  256. data/lib/generators/test_unit/plugin/templates/test_helper.rb +3 -0
  257. data/lib/generators/test_unit/scaffold/scaffold_generator.rb +18 -0
  258. data/lib/generators/test_unit/scaffold/templates/functional_test.rb +47 -0
  259. data/lib/rails.rb +95 -0
  260. data/lib/rails/all.rb +14 -0
  261. data/lib/rails/application.rb +125 -0
  262. data/lib/rails/application/bootstrap.rb +85 -0
  263. data/lib/rails/application/configurable.rb +19 -0
  264. data/lib/rails/application/configuration.rb +86 -0
  265. data/lib/rails/application/finisher.rb +49 -0
  266. data/lib/rails/application/metal_loader.rb +50 -0
  267. data/lib/rails/application/railties.rb +31 -0
  268. data/lib/rails/application/routes_reloader.rb +46 -0
  269. data/lib/rails/backtrace_cleaner.rb +54 -0
  270. data/lib/rails/code_statistics.rb +107 -0
  271. data/lib/rails/commands.rb +72 -0
  272. data/lib/rails/commands/application.rb +13 -0
  273. data/lib/rails/commands/console.rb +55 -0
  274. data/lib/rails/commands/dbconsole.rb +104 -0
  275. data/lib/rails/commands/destroy.rb +9 -0
  276. data/lib/rails/commands/generate.rb +9 -0
  277. data/lib/rails/commands/performance/benchmarker.rb +23 -0
  278. data/lib/rails/commands/performance/profiler.rb +46 -0
  279. data/lib/rails/commands/plugin.rb +542 -0
  280. data/lib/rails/commands/runner.rb +51 -0
  281. data/lib/rails/commands/server.rb +75 -0
  282. data/lib/rails/commands/update.rb +9 -0
  283. data/lib/rails/configuration.rb +191 -0
  284. data/lib/rails/console/app.rb +33 -0
  285. data/lib/rails/console/helpers.rb +5 -0
  286. data/lib/rails/console/sandbox.rb +6 -0
  287. data/lib/rails/deprecation.rb +62 -0
  288. data/lib/rails/dispatcher.rb +24 -0
  289. data/lib/rails/engine.rb +130 -0
  290. data/lib/rails/engine/configurable.rb +25 -0
  291. data/lib/rails/engine/configuration.rb +49 -0
  292. data/lib/rails/generators.rb +289 -0
  293. data/lib/rails/generators/actions.rb +309 -0
  294. data/lib/rails/generators/active_model.rb +78 -0
  295. data/lib/rails/generators/base.rb +362 -0
  296. data/lib/rails/generators/generated_attribute.rb +48 -0
  297. data/lib/rails/generators/migration.rb +64 -0
  298. data/lib/rails/generators/named_base.rb +95 -0
  299. data/lib/rails/generators/resource_helpers.rb +80 -0
  300. data/lib/rails/generators/test_case.rb +239 -0
  301. data/lib/rails/initializable.rb +97 -0
  302. data/lib/rails/paths.rb +144 -0
  303. data/lib/rails/performance_test_help.rb +3 -0
  304. data/lib/rails/plugin.rb +64 -0
  305. data/lib/rails/rack.rb +8 -0
  306. data/lib/rails/rack/debugger.rb +23 -0
  307. data/lib/rails/rack/log_tailer.rb +33 -0
  308. data/lib/rails/rack/logger.rb +34 -0
  309. data/lib/rails/rack/static.rb +5 -0
  310. data/lib/rails/railtie.rb +74 -0
  311. data/lib/rails/railtie/configurable.rb +23 -0
  312. data/lib/rails/railtie/configuration.rb +9 -0
  313. data/lib/rails/railties_path.rb +1 -0
  314. data/lib/rails/ruby_version_check.rb +10 -0
  315. data/lib/rails/rubyprof_ext.rb +35 -0
  316. data/lib/rails/source_annotation_extractor.rb +102 -0
  317. data/lib/rails/subscriber.rb +108 -0
  318. data/lib/rails/subscriber/test_helper.rb +98 -0
  319. data/lib/rails/tasks.rb +16 -0
  320. data/lib/rails/tasks/annotations.rake +20 -0
  321. data/lib/rails/tasks/documentation.rake +96 -0
  322. data/lib/rails/tasks/framework.rake +69 -0
  323. data/lib/rails/tasks/log.rake +9 -0
  324. data/lib/rails/tasks/middleware.rake +7 -0
  325. data/lib/rails/tasks/misc.rake +71 -0
  326. data/lib/rails/tasks/routes.rake +17 -0
  327. data/lib/rails/tasks/statistics.rake +16 -0
  328. data/lib/rails/tasks/tmp.rake +37 -0
  329. data/lib/rails/test_help.rb +30 -0
  330. data/lib/rails/test_unit/railtie.rb +17 -0
  331. data/lib/rails/test_unit/testing.rake +130 -0
  332. data/lib/rails/version.rb +9 -0
  333. data/lib/rails/webrick_server.rb +156 -0
  334. metadata +427 -0
@@ -0,0 +1,342 @@
1
+ h2. AJAX on Rails
2
+
3
+ This guide covers the built-in Ajax/Javascript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics:
4
+
5
+ * Quick introduction to AJAX and related technologies
6
+ * Handling Javascript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us
7
+ * Testing Javascript functionality
8
+
9
+ endprologue.
10
+
11
+ h3. Hello AJAX - a Quick Intro
12
+
13
+ If you are a 'show me the code' type of person, you might want to skip this part and jump to the RJS section right away. However, I would really recommend to read it - you'll need the basics of DOM, http requests and other topics discussed here to really understand Ajax on Rails.
14
+
15
+ h4. Asynchronous Javascript + XML
16
+
17
+ Basic terminology, new style of creating web apps
18
+
19
+ h4. The DOM
20
+
21
+ basics of the DOM, how is it built, properties, features, why is it central to AJAX
22
+
23
+ h4. Standard HTML communication vs AJAX
24
+
25
+ How do 'standard' and AJAX requests differ, why does this matter for understanding AJAX on Rails (tie in for *_remote helpers, the next section)
26
+
27
+
28
+
29
+
30
+
31
+
32
+ h3. Built-in Rails Helpers
33
+
34
+ Rails' Javascript framework of choice is "Prototype":http://www.prototypejs.org. Prototype is a generic-purpose Javascript framework that aims to ease the development of dynamic web applications by offering DOM manipulation, AJAX and other Javascript functionality ranging from utility functions to object oriented constructs. It is not specifically written for any language, so Rails provides a set of helpers to enable seamless integration of Prototype with your Rails views.
35
+
36
+ To get access to these helpers, all you have to do is to include the prototype framework in your pages - typically in your master layout, application.html.erb - like so:
37
+ <ruby>
38
+ javascript_include_tag 'prototype'
39
+ </ruby>
40
+
41
+ You are ready to add some AJAX love to your Rails app!
42
+
43
+ h4. The Quintessential AJAX Rails Helper: link_to_remote
44
+
45
+ Let's start with the the probably most often used helper: +link_to_remote+, which has an interesting feature from the documentation point of view: the options supplied to +link_to_remote+ are shared by all other AJAX helpers, so learning the mechanics and options of +link_to_remote+ is a great help when using other helpers.
46
+
47
+ The signature of +link_to_remote+ function is the same as that of the standard +link_to+ helper:
48
+
49
+ <ruby>
50
+ def link_to_remote(name, options = {}, html_options = nil)
51
+ </ruby>
52
+
53
+ And here is a simple example of link_to_remote in action:
54
+
55
+ <ruby>
56
+ link_to_remote "Add to cart",
57
+ :url => add_to_cart_url(product.id),
58
+ :update => "cart"
59
+ </ruby>
60
+
61
+ * The very first parameter, a string, is the text of the link which appears on the page.
62
+
63
+ * The second parameter, the +options+ hash is the most interesting part as it has the AJAX specific stuff:
64
+ ** *:url* This is the only parameter that is always required to generate the simplest remote link (technically speaking, it is not required, you can pass an empty +options+ hash to +link_to_remote+ - but in this case the URL used for the POST request will be equal to your current URL which is probably not your intention). This URL points to your AJAX action handler. The URL is typically specified by Rails REST view helpers, but you can use the +url_for+ format too.
65
+ ** *:update* There are basically two ways of injecting the server response into the page: One is involving RJS and we will discuss it in the next chapter, and the other is specifying a DOM id of the element we would like to update. The above example demonstrates the simplest way of accomplishing this - however, we are in trouble if the server responds with an error message because that will be injected into the page too! However, Rails has a solution for this situation:
66
+
67
+ <ruby>
68
+ link_to_remote "Add to cart",
69
+ :url => add_to_cart_url(product),
70
+ :update => { :success => "cart", :failure => "error" }
71
+ </ruby>
72
+
73
+ If the server returns 200, the output of the above example is equivalent to our first, simple one. However, in case of error, the element with the DOM id +error+ is updated rather than the +cart+ element.
74
+
75
+ ** *position* By default (i.e. when not specifying this option, like in the examples before) the repsonse is injected into the element with the specified DOM id, replacing the original content of the element (if there was any). You might want to alter this behavior by keeping the original content - the only question is where to place the new content? This can specified by the +position+ parameter, with four possibilities:
76
+ *** +:before+ Inserts the response text just before the target element. More precisely, it creates a text node from the response and inserts it as the left sibling of the target element.
77
+ *** +:after+ Similar behavior to +:before+, but in this case the response is inserted after the target element.
78
+ *** +:top+ Inserts the text into the target element, before it's original content. If the target element was empty, this is equivalent with not specifying +:position+ at all.
79
+ *** +:bottom+ The counterpart of +:top+: the response is inserted after the target element's original content.
80
+
81
+ A typical example of using +:bottom+ is inserting a new &lt;li&gt; element into an existing list:
82
+
83
+ <ruby>
84
+ link_to_remote "Add new item",
85
+ :url => items_url,
86
+ :update => 'item_list',
87
+ :position => :bottom
88
+ </ruby>
89
+
90
+ ** *:method* Most typically you want to use a POST request when adding a remote link to your view so this is the default behavior. However, sometimes you'll want to update (PUT) or delete/destroy (DELETE) something and you can specify this with the +:method+ option. Let's see an example for a typical AJAX link for deleting an item from a list:
91
+
92
+ <ruby>
93
+ link_to_remote "Delete the item",
94
+ :url => item_url(item),
95
+ :method => :delete
96
+ </ruby>
97
+
98
+ Note that if we wouldn't override the default behavior (POST), the above snippet would route to the create action rather than destroy.
99
+
100
+ ** *JavaScript filters* You can customize the remote call further by wrapping it with some JavaScript code. Let's say in the previous example, when deleting a link, you'd like to ask for a confirmation by showing a simple modal text box to the user. This is a typical example what you can accomplish with these options - let's see them one by one:
101
+ *** +:confirm+ =&gt; +msg+ Pops up a JavaScript confirmation dialog, displaying +msg+. If the user chooses 'OK', the request is launched, otherwise canceled.
102
+ *** +:condition+ =&gt; +code+ Evaluates +code+ (which should evaluate to a boolean) and proceeds if it's true, cancels the request otherwise.
103
+ *** +:before+ =&gt; +code+ Evaluates the +code+ just before launching the request. The output of the code has no influence on the execution. Typically used show a progress indicator (see this in action in the next example).
104
+ *** +:after+ =&gt; +code+ Evaluates the +code+ after launching the request. Note that this is different from the +:success+ or +:complete+ callback (covered in the next section) since those are triggered after the request is completed, while the code snippet passed to +:after+ is evaluated after the remote call is made. A common example is to disable elements on the page or otherwise prevent further action while the request is completed.
105
+ *** +:submit+ =&gt; +dom_id+ This option does not make sense for +link_to_remote+, but we'll cover it for the sake of completeness. By default, the parent element of the form elements the user is going to submit is the current form - use this option if you want to change the default behavior. By specifying this option you can change the parent element to the element specified by the DOM id +dom_id+.
106
+ *** +:with+ &gt; +code+ The JavaScript code snippet in +code+ is evaluated and added to the request URL as a parameter (or set of parameters). Therefore, +code+ should return a valid URL query string (like "item_type=8" or "item_type=8&sort=true"). Usually you want to obtain some value(s) from the page - let's see an example:
107
+
108
+ <ruby>
109
+ link_to_remote "Update record",
110
+ :url => record_url(record),
111
+ :method => :put,
112
+ :with => "'status=' + 'encodeURIComponent($('status').value) + '&completed=' + $('completed')"
113
+ </ruby>
114
+
115
+ This generates a remote link which adds 2 parameters to the standard URL generated by Rails, taken from the page (contained in the elements matched by the 'status' and 'completed' DOM id).
116
+
117
+ ** *Callbacks* Since an AJAX call is typically asynchronous, as it's name suggests (this is not a rule, and you can fire a synchronous request - see the last option, +:type+) your only way of communicating with a request once it is fired is via specifying callbacks. There are six options at your disposal (in fact 508, counting all possible response types, but these six are the most frequent and therefore specified by a constant):
118
+ *** +:loading:+ =&gt; +code+ The request is in the process of receiving the data, but the transfer is not completed yet.
119
+ *** +:loaded:+ =&gt; +code+ The transfer is completed, but the data is not processed and returned yet
120
+ *** +:interactive:+ =&gt; +code+ One step after +:loaded+: The data is fully received and being processed
121
+ *** +:success:+ =&gt; +code+ The data is fully received, parsed and the server responded with "200 OK"
122
+ *** +:failure:+ =&gt; +code+ The data is fully received, parsed and the server responded with *anything* but "200 OK" (typically 404 or 500, but in general with any status code ranging from 100 to 509)
123
+ *** +:complete:+ =&gt; +code+ The combination of the previous two: The request has finished receiving and parsing the data, and returned a status code (which can be anything).
124
+ *** Any other status code ranging from 100 to 509: Additionally you might want to check for other HTTP status codes, such as 404. In this case simply use the status code as a number:
125
+ <ruby>
126
+ link_to_remote "Add new item",
127
+ :url => items_url,
128
+ :update => "item_list",
129
+ 404 => "alert('Item not found!')"
130
+ </ruby>
131
+ Let's see a typical example for the most frequent callbacks, +:success+, +:failure+ and +:complete+ in action:
132
+ <ruby>
133
+ link_to_remote "Add new item",
134
+ :url => items_url,
135
+ :update => "item_list",
136
+ :before => "$('progress').show()",
137
+ :complete => "$('progress').hide()",
138
+ :success => "display_item_added(request)",
139
+ :failure => "display_error(request)",
140
+ </ruby>
141
+ ** *:type* If you want to fire a synchronous request for some obscure reason (blocking the browser while the request is processed and doesn't return a status code), you can use the +:type+ option with the value of +:synchronous+.
142
+ * Finally, using the +html_options+ parameter you can add HTML attributes to the generated tag. It works like the same parameter of the +link_to+ helper. There are interesting side effects for the +href+ and +onclick+ parameters though:
143
+ ** If you specify the +href+ parameter, the AJAX link will degrade gracefully, i.e. the link will point to the URL even if JavaScript is disabled in the client browser
144
+ ** +link_to_remote+ gains it's AJAX behavior by specifying the remote call in the onclick handler of the link. If you supply +html_options[:onclick]+ you override the default behavior, so use this with care!
145
+
146
+ We are finished with +link_to_remote+. I know this is quite a lot to digest for one helper function, but remember, these options are common for all the rest of the Rails view helpers, so we will take a look at the differences / additional parameters in the next sections.
147
+
148
+ h4. AJAX Forms
149
+
150
+ There are three different ways of adding AJAX forms to your view using Rails Prototype helpers. They are slightly different, but striving for the same goal: instead of submitting the form using the standard HTTP request/response cycle, it is submitted asynchronously, thus not reloading the page. These methods are the following:
151
+
152
+ * +remote_form_for+ (and it's alias +form_remote_for+) is tied to Rails most tightly of the three since it takes a resource, model or array of resources (in case of a nested resource) as a parameter.
153
+ * +form_remote_tag+ AJAXifies the form by serializing and sending it's data in the background
154
+ * +submit_to_remote+ and +button_to_remote+ is more rarely used than the previous two. Rather than creating an AJAX form, you add a button/input
155
+
156
+ Let's se them in action one by one!
157
+
158
+ h5. +remote_form_for+
159
+
160
+ h5. +form_remote_tag+
161
+
162
+ h5. +submit_to_remote+
163
+
164
+ h4. Observing Elements
165
+
166
+ h5. +observe_field+
167
+
168
+ h5. +observe_form+
169
+
170
+ h4. Calling a Function Periodically
171
+
172
+ h5. +periodically_call_remote+
173
+
174
+
175
+ h4. Miscellaneous Functionality
176
+
177
+ h5. +remote_function+
178
+
179
+ h5. +update_page+
180
+
181
+
182
+ h3. JavaScript the Rails way: RJS
183
+
184
+ In the last section we sent some AJAX requests to the server, and inserted the HTML response into the page (with the +:update+ option). However, sometimes a more complicated interaction with the page is needed, which you can either achieve with JavaScript... or with RJS! You are sending JavaScript instructions to the server in both cases, but while in the former case you have to write vanilla JavaScript, in the second you can code Rails, and sit back while Rails generates the JavaScript for you - so basically RJS is a Ruby DSL to write JavaScript in your Rails code.
185
+
186
+ h4. Javascript without RJS
187
+
188
+ First we'll check out how to send JavaScript to the server manually. You are practically never going to need this, but it's interesting to understand what's going on under the hood.
189
+
190
+ <ruby>
191
+ def javascript_test
192
+ render :text => "alert('Hello, world!')",
193
+ :content_type => "text/javascript"
194
+ end
195
+ </ruby>
196
+
197
+ (Note: if you want to test the above method, create a +link_to_remote+ with a single parameter - +:url+, pointing to the +javascript_test+ action)
198
+
199
+ What happens here is that by specifying the Content-Type header variable, we instruct the browser to evaluate the text we are sending over (rather than displaying it as plain text, which is the default behavior).
200
+
201
+ h4. Inline RJS
202
+
203
+ As we said, the purpose of RJS is to write Ruby which is then auto-magically turned into JavaScript by Rails. The above example didn't look too Ruby-esque so let's see how to do it the Rails way:
204
+
205
+ <ruby>
206
+ def javascript_test
207
+ render :update do |page|
208
+ page.alert "Hello from inline RJS"
209
+ end
210
+ end
211
+ </ruby>
212
+
213
+ The above code snippet does exactly the same as the one in the previous section - going about it much more elegantly though. You don't need to worry about headers,write ugly JavaScript code into a string etc. When the first parameter to +render+ is +:update+, Rails expects a block with a single parameter (+page+ in our case, which is the traditional naming convention) which is an instance of the JavaScriptGenerator:"http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper/JavaScriptGenerator/GeneratorMethods.html" object. As it's name suggests, JavaScriptGenerator is responsible for generating JavaScript from your Ruby code. You can execute multiple method calls on the +page+ instance - it's all turned into JavaScript code and sent to the server with the appropriate Content Type, "text/javascript".
214
+
215
+ h4. RJS Templates
216
+
217
+ If you don't want to clutter your controllers with view code (especially when your inline RJS is more than a few lines), you can move your RJS code to a template file. RJS templates should go to the +/app/views/+ directory, just as +.html.erb+ or any other view files of the appropriate controller, conventionally named +js.rjs+.
218
+
219
+ To rewrite the above example, you can leave the body of the action empty, and create a RJS template named +javascript_test.js.rjs+, containing the following line:
220
+
221
+ <ruby>
222
+ page.alert "Hello from inline RJS"
223
+ </ruby>
224
+
225
+ h4. RJS Reference
226
+
227
+ In this section we'll go through the methods RJS offers.
228
+
229
+ h5. JavaScriptGenerator Methods
230
+
231
+ h6. DOM Element Manipulation
232
+
233
+ It is possible to manipulate multiple elements at once through the +page+ JavaScriptGenerator instance. Let's see this in action:
234
+
235
+ <ruby>
236
+ page.show :div_one, :div_two
237
+ page.hide :div_one
238
+ page.remove :div_one, :div_two, :div_three
239
+ page.toggle :other_div
240
+ </ruby>
241
+
242
+ The above methods (+show+, +hide+, +remove+, +toggle+) have the same semantics as the Prototype methods of the same name. You can pass an arbitrary number (but at least one) of DOM ids to these calls.
243
+
244
+
245
+ h6. Inserting and Replacing Content
246
+
247
+ You can insert content into an element on the page with the +insert_html+ method:
248
+
249
+ <ruby>
250
+ page.insert_html :top, :result, '42'
251
+ </ruby>
252
+
253
+ The first parameter is the position of the new content relative to the element specified by the second parameter, a DOM id.
254
+
255
+ Position can be one of these four values:
256
+
257
+ *** +:before+ Inserts the response text just before the target element.
258
+ *** +:after+ The response is inserted after the target element.
259
+ *** +:top+ Inserts the text into the target element, before it's original content.
260
+ *** +:bottom+ The counterpart of +:top+: the response is inserted after the target element's original content.
261
+
262
+ The third parameter can either be a string, or a hash of options to be passed to ActionView::Base#render - for example:
263
+
264
+ <ruby>
265
+ page.insert_html :top, :result, :partial => "the_answer"
266
+ </ruby>
267
+
268
+ You can replace the contents (innerHTML) of an element with the +replace_html+ method. The only difference is that since it's clear where should the new content go, there is no need for a position parameter - so +replace_html+ takes only two arguments,
269
+ the DOM id of the element you wish to modify and a string or a hash of options to be passed to ActionView::Base#render.
270
+
271
+ h6. Delay
272
+
273
+ You can delay the execution of a block of code with +delay+:
274
+
275
+ <ruby>
276
+ page.delay(10) { page.alert('Hey! Just waited 10 seconds') }
277
+ </ruby>
278
+
279
+ +delay+ takes one parameter (time to wait in seconds) and a block which will be executed after the specified time has passed - whatever else follows a +page.delay+ line is executed immediately, the delay affects only the code in the block.
280
+
281
+ h6. Reloading and Redirecting
282
+
283
+ You can reload the page with the +reload+ method:
284
+
285
+ <ruby>
286
+ page.reload
287
+ </ruby>
288
+
289
+ When using AJAX, you can't rely on the standard +redirect_to+ controller method - you have to use the +page+'s instance method, also called +redirect_to+:
290
+
291
+ <ruby>
292
+ page.redirect_to some_url
293
+ </ruby>
294
+
295
+ h6. Generating Arbitrary JavaScript
296
+
297
+ Sometimes even the full power of RJS is not enough to accomplish everything, but you still don't want to drop to pure JavaScript. A nice golden mean is offered by the combination of +<<+, +assign+ and +call+ methods:
298
+
299
+ <ruby>
300
+ page << "alert('1+1 equals 3')"
301
+ </ruby>
302
+
303
+ So +<<+ is used to execute an arbitrary JavaScript statement, passed as string to the method. The above code is equivalent to:
304
+
305
+ <ruby>
306
+ page.assign :result, 3
307
+ page.call :alert, '1+1 equals ' + result
308
+ </ruby>
309
+
310
+ +assign+ simply assigns a value to a variable. +call+ is similar to +<<+ with a slightly different syntax: the first parameter is the name of the function to call, followed by the list of parameters passed to the function.
311
+
312
+ h6. Class Proxies
313
+
314
+ h5. Element Proxies
315
+
316
+ h5. Collection Proxies
317
+
318
+ h5. RJS Helpers
319
+
320
+
321
+
322
+ h3. I Want my Yellow Thingy: Quick overview of Script.aculo.us
323
+
324
+ h4. Introduction
325
+
326
+ h4. Visual Effects
327
+
328
+ h4. Drag and Drop
329
+
330
+
331
+
332
+ h3. Testing Javascript
333
+
334
+ Javascript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with Javascript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it:
335
+
336
+ * (Fire)Watir
337
+ * Selenium
338
+ * Celerity/Culerity
339
+ * Cucumber+Webrat
340
+ * Mention stuff like screw.unit/jsSpec
341
+
342
+ Note to self: check out the RailsConf JS testing video
@@ -0,0 +1,1816 @@
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_all_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
+ * +:touch+
604
+ * +:validate+
605
+
606
+ h6. +:autosave+
607
+
608
+ 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.
609
+
610
+ h6. +:class_name+
611
+
612
+ 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:
613
+
614
+ <ruby>
615
+ class Order < ActiveRecord::Base
616
+ belongs_to :customer, :class_name => "Patron"
617
+ end
618
+ </ruby>
619
+
620
+ h6. +:conditions+
621
+
622
+ The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
623
+
624
+ <ruby>
625
+ class Order < ActiveRecord::Base
626
+ belongs_to :customer, :conditions => "active = 1"
627
+ end
628
+ </ruby>
629
+
630
+ h6. +:counter_cache+
631
+
632
+ The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
633
+
634
+ <ruby>
635
+ class Order < ActiveRecord::Base
636
+ belongs_to :customer
637
+ end
638
+ class Customer < ActiveRecord::Base
639
+ has_many :orders
640
+ end
641
+ </ruby>
642
+
643
+ 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:
644
+
645
+ <ruby>
646
+ class Order < ActiveRecord::Base
647
+ belongs_to :customer, :counter_cache => true
648
+ end
649
+ class Customer < ActiveRecord::Base
650
+ has_many :orders
651
+ end
652
+ </ruby>
653
+
654
+ With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +size+ method.
655
+
656
+ 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:
657
+
658
+ <ruby>
659
+ class Order < ActiveRecord::Base
660
+ belongs_to :customer, :counter_cache => :count_of_orders
661
+ end
662
+ class Customer < ActiveRecord::Base
663
+ has_many :orders
664
+ end
665
+ </ruby>
666
+
667
+ Counter cache columns are added to the containing model's list of read-only attributes through +attr_readonly+.
668
+
669
+ h6. +:dependent+
670
+
671
+ 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.
672
+
673
+ 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.
674
+
675
+ h6. +:foreign_key+
676
+
677
+ 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:
678
+
679
+ <ruby>
680
+ class Order < ActiveRecord::Base
681
+ belongs_to :customer, :class_name => "Patron",
682
+ :foreign_key => "patron_id"
683
+ end
684
+ </ruby>
685
+
686
+ TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
687
+
688
+ h6. +:include+
689
+
690
+ 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:
691
+
692
+ <ruby>
693
+ class LineItem < ActiveRecord::Base
694
+ belongs_to :order
695
+ end
696
+
697
+ class Order < ActiveRecord::Base
698
+ belongs_to :customer
699
+ has_many :line_items
700
+ end
701
+
702
+ class Customer < ActiveRecord::Base
703
+ has_many :orders
704
+ end
705
+ </ruby>
706
+
707
+ 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:
708
+
709
+ <ruby>
710
+ class LineItem < ActiveRecord::Base
711
+ belongs_to :order, :include => :customer
712
+ end
713
+
714
+ class Order < ActiveRecord::Base
715
+ belongs_to :customer
716
+ has_many :line_items
717
+ end
718
+
719
+ class Customer < ActiveRecord::Base
720
+ has_many :orders
721
+ end
722
+ </ruby>
723
+
724
+ 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.
725
+
726
+ h6. +:polymorphic+
727
+
728
+ 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>.
729
+
730
+ h6. +:readonly+
731
+
732
+ If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
733
+
734
+ h6. +:select+
735
+
736
+ 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.
737
+
738
+ 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.
739
+
740
+ h6. +:touch+
741
+
742
+ If you set the +:touch+ option to +:true+, then the +updated_at+ or +updated_on+ timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:
743
+
744
+ <ruby>
745
+ class Order < ActiveRecord::Base
746
+ belongs_to :customer, :touch => true
747
+ end
748
+
749
+ class Customer < ActiveRecord::Base
750
+ has_many :orders
751
+ end
752
+ </ruby>
753
+
754
+ In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:
755
+
756
+ <ruby>
757
+ class Order < ActiveRecord::Base
758
+ belongs_to :customer, :touch => :orders_updated_at
759
+ end
760
+ </ruby>
761
+
762
+ h6. +:validate+
763
+
764
+ 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.
765
+
766
+ h5. How To Know Whether There's an Associated Object?
767
+
768
+ To know whether there's and associated object just check <tt><em>association</em>.nil?</tt>:
769
+
770
+ <ruby>
771
+ if @order.customer.nil?
772
+ @msg = "No customer found for this order"
773
+ end
774
+ </ruby>
775
+
776
+ h5. When are Objects Saved?
777
+
778
+ Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either.
779
+
780
+ h4. +has_one+ Association Reference
781
+
782
+ 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.
783
+
784
+ h5. Methods Added by +has_one+
785
+
786
+ When you declare a +has_one+ association, the declaring class automatically gains four methods related to the association:
787
+
788
+ * <tt><em>association</em>(force_reload = false)</tt>
789
+ * <tt><em>association</em>=(associate)</tt>
790
+ * <tt>build_<em>association</em>(attributes = {})</tt>
791
+ * <tt>create_<em>association</em>(attributes = {})</tt>
792
+
793
+ 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:
794
+
795
+ <ruby>
796
+ class Supplier < ActiveRecord::Base
797
+ has_one :account
798
+ end
799
+ </ruby>
800
+
801
+ Each instance of the +Supplier+ model will have these methods:
802
+
803
+ <ruby>
804
+ account
805
+ account=
806
+ build_account
807
+ create_account
808
+ </ruby>
809
+
810
+ h6. <tt><em>association</em>(force_reload = false)</tt>
811
+
812
+ The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.
813
+
814
+ <ruby>
815
+ @account = @supplier.account
816
+ </ruby>
817
+
818
+ 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.
819
+
820
+ h6. <tt><em>association</em>=(associate)</tt>
821
+
822
+ 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.
823
+
824
+ <ruby>
825
+ @supplier.account = @account
826
+ </ruby>
827
+
828
+ h6. <tt>build_<em>association</em>(attributes = {})</tt>
829
+
830
+ 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.
831
+
832
+ <ruby>
833
+ @account = @supplier.build_account(:terms => "Net 30")
834
+ </ruby>
835
+
836
+ h6. <tt>create_<em>association</em>(attributes = {})</tt>
837
+
838
+ 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).
839
+
840
+ <ruby>
841
+ @account = @supplier.create_account(:terms => "Net 30")
842
+ </ruby>
843
+
844
+ h5. Options for +has_one+
845
+
846
+ 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:
847
+
848
+ <ruby>
849
+ class Supplier < ActiveRecord::Base
850
+ has_one :account, :class_name => "Billing", :dependent => :nullify
851
+ end
852
+ </ruby>
853
+
854
+ The +has_one+ association supports these options:
855
+
856
+ * +:as+
857
+ * +:autosave+
858
+ * +:class_name+
859
+ * +:conditions+
860
+ * +:dependent+
861
+ * +:foreign_key+
862
+ * +:include+
863
+ * +:order+
864
+ * +:primary_key+
865
+ * +:readonly+
866
+ * +:select+
867
+ * +:source+
868
+ * +:source_type+
869
+ * +:through+
870
+ * +:validate+
871
+
872
+ h6. +:as+
873
+
874
+ 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>.
875
+
876
+ h6. +:autosave+
877
+
878
+ 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.
879
+
880
+ h6. +:class_name+
881
+
882
+ 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:
883
+
884
+ <ruby>
885
+ class Supplier < ActiveRecord::Base
886
+ has_one :account, :class_name => "Billing"
887
+ end
888
+ </ruby>
889
+
890
+ h6. +:conditions+
891
+
892
+ The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
893
+
894
+ <ruby>
895
+ class Supplier < ActiveRecord::Base
896
+ has_one :account, :conditions => "confirmed = 1"
897
+ end
898
+ </ruby>
899
+
900
+ h6. +:dependent+
901
+
902
+ 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+.
903
+
904
+ h6. +:foreign_key+
905
+
906
+ 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:
907
+
908
+ <ruby>
909
+ class Supplier < ActiveRecord::Base
910
+ has_one :account, :foreign_key => "supp_id"
911
+ end
912
+ </ruby>
913
+
914
+ TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
915
+
916
+ h6. +:include+
917
+
918
+ 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:
919
+
920
+ <ruby>
921
+ class Supplier < ActiveRecord::Base
922
+ has_one :account
923
+ end
924
+
925
+ class Account < ActiveRecord::Base
926
+ belongs_to :supplier
927
+ belongs_to :representative
928
+ end
929
+
930
+ class Representative < ActiveRecord::Base
931
+ has_many :accounts
932
+ end
933
+ </ruby>
934
+
935
+ 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:
936
+
937
+ <ruby>
938
+ class Supplier < ActiveRecord::Base
939
+ has_one :account, :include => :representative
940
+ end
941
+
942
+ class Account < ActiveRecord::Base
943
+ belongs_to :supplier
944
+ belongs_to :representative
945
+ end
946
+
947
+ class Representative < ActiveRecord::Base
948
+ has_many :accounts
949
+ end
950
+ </ruby>
951
+
952
+ h6. +:order+
953
+
954
+ 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.
955
+
956
+ h6. +:primary_key+
957
+
958
+ 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.
959
+
960
+ h6. +:readonly+
961
+
962
+ If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
963
+
964
+ h6. +:select+
965
+
966
+ 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.
967
+
968
+ h6. +:source+
969
+
970
+ The +:source+ option specifies the source association name for a +has_one :through+ association.
971
+
972
+ h6. +:source_type+
973
+
974
+ The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
975
+
976
+ h6. +:through+
977
+
978
+ 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>.
979
+
980
+ h6. +:validate+
981
+
982
+ 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.
983
+
984
+ h5. How To Know Whether There's an Associated Object?
985
+
986
+ To know whether there's and associated object just check <tt><em>association</em>.nil?</tt>:
987
+
988
+ <ruby>
989
+ if @supplier.account.nil?
990
+ @msg = "No account found for this supplier"
991
+ end
992
+ </ruby>
993
+
994
+ h5. When are Objects Saved?
995
+
996
+ 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.
997
+
998
+ If either of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
999
+
1000
+ 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.
1001
+
1002
+ 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.
1003
+
1004
+ h4. +has_many+ Association Reference
1005
+
1006
+ 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.
1007
+
1008
+ h5. Methods Added
1009
+
1010
+ When you declare a +has_many+ association, the declaring class automatically gains 13 methods related to the association:
1011
+
1012
+ * <tt><em>collection</em>(force_reload = false)</tt>
1013
+ * <tt><em>collection</em><<(object, ...)</tt>
1014
+ * <tt><em>collection</em>.delete(object, ...)</tt>
1015
+ * <tt><em>collection</em>=objects</tt>
1016
+ * <tt><em>collection_singular</em>_ids</tt>
1017
+ * <tt><em>collection_singular</em>_ids=ids</tt>
1018
+ * <tt><em>collection</em>.clear</tt>
1019
+ * <tt><em>collection</em>.empty?</tt>
1020
+ * <tt><em>collection</em>.size</tt>
1021
+ * <tt><em>collection</em>.find(...)</tt>
1022
+ * <tt><em>collection</em>.exists?(...)</tt>
1023
+ * <tt><em>collection</em>.build(attributes = {}, ...)</tt>
1024
+ * <tt><em>collection</em>.create(attributes = {})</tt>
1025
+
1026
+ 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:
1027
+
1028
+ <ruby>
1029
+ class Customer < ActiveRecord::Base
1030
+ has_many :orders
1031
+ end
1032
+ </ruby>
1033
+
1034
+ Each instance of the customer model will have these methods:
1035
+
1036
+ <ruby>
1037
+ orders(force_reload = false)
1038
+ orders<<(object, ...)
1039
+ orders.delete(object, ...)
1040
+ orders=objects
1041
+ order_ids
1042
+ order_ids=ids
1043
+ orders.clear
1044
+ orders.empty?
1045
+ orders.size
1046
+ orders.find(...)
1047
+ orders.exists?(...)
1048
+ orders.build(attributes = {}, ...)
1049
+ orders.create(attributes = {})
1050
+ </ruby>
1051
+
1052
+ h6. <tt><em>collection</em>(force_reload = false)</tt>
1053
+
1054
+ 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.
1055
+
1056
+ <ruby>
1057
+ @orders = @customer.orders
1058
+ </ruby>
1059
+
1060
+ h6. <tt><em>collection</em><<(object, ...)</tt>
1061
+
1062
+ 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.
1063
+
1064
+ <ruby>
1065
+ @customer.orders << @order1
1066
+ </ruby>
1067
+
1068
+ h6. <tt><em>collection</em>.delete(object, ...)</tt>
1069
+
1070
+ The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by setting their foreign keys to +NULL+.
1071
+
1072
+ <ruby>
1073
+ @customer.orders.delete(@order1)
1074
+ </ruby>
1075
+
1076
+ WARNING: Objects will be in addition destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+.
1077
+
1078
+
1079
+ h6. <tt><em>collection</em>=objects</tt>
1080
+
1081
+ The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
1082
+
1083
+ h6. <tt><em>collection_singular</em>_ids</tt>
1084
+
1085
+ The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.
1086
+
1087
+ <ruby>
1088
+ @order_ids = @customer.order_ids
1089
+ </ruby>
1090
+
1091
+ h6. <tt><em>collection_singular</em>_ids=ids</tt>
1092
+
1093
+ 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.
1094
+
1095
+ h6. <tt><em>collection</em>.clear</tt>
1096
+
1097
+ 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+.
1098
+
1099
+ h6. <tt><em>collection</em>.empty?</tt>
1100
+
1101
+ The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.
1102
+
1103
+ <ruby>
1104
+ <% if @customer.orders.empty? %>
1105
+ No Orders Found
1106
+ <% end %>
1107
+ </ruby>
1108
+
1109
+ h6. <tt><em>collection</em>.size</tt>
1110
+
1111
+ The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.
1112
+
1113
+ <ruby>
1114
+ @order_count = @customer.orders.size
1115
+ </ruby>
1116
+
1117
+ h6. <tt><em>collection</em>.find(...)</tt>
1118
+
1119
+ The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
1120
+
1121
+ <ruby>
1122
+ @open_orders = @customer.orders.find(:all, :conditions => "open = 1")
1123
+ </ruby>
1124
+
1125
+ h6. <tt><em>collection</em>.exists?(...)</tt>
1126
+
1127
+ The <tt><em>collection</em>.exists?</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?+.
1128
+
1129
+ h6. <tt><em>collection</em>.build(attributes = {}, ...)</tt>
1130
+
1131
+ 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.
1132
+
1133
+ <ruby>
1134
+ @order = @customer.orders.build(:order_date => Time.now,
1135
+ :order_number => "A12345")
1136
+ </ruby>
1137
+
1138
+ h6. <tt><em>collection</em>.create(attributes = {})</tt>
1139
+
1140
+ 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).
1141
+
1142
+ <ruby>
1143
+ @order = @customer.orders.create(:order_date => Time.now,
1144
+ :order_number => "A12345")
1145
+ </ruby>
1146
+
1147
+ h5. Options for +has_many+
1148
+
1149
+ 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:
1150
+
1151
+ <ruby>
1152
+ class Customer < ActiveRecord::Base
1153
+ has_many :orders, :dependent => :delete_all, :validate => :false
1154
+ end
1155
+ </ruby>
1156
+
1157
+ The +has_many+ association supports these options:
1158
+
1159
+ * +:as+
1160
+ * +:autosave+
1161
+ * +:class_name+
1162
+ * +:conditions+
1163
+ * +:counter_sql+
1164
+ * +:dependent+
1165
+ * +:extend+
1166
+ * +:finder_sql+
1167
+ * +:foreign_key+
1168
+ * +:group+
1169
+ * +:include+
1170
+ * +:limit+
1171
+ * +:offset+
1172
+ * +:order+
1173
+ * +:primary_key+
1174
+ * +:readonly+
1175
+ * +:select+
1176
+ * +:source+
1177
+ * +:source_type+
1178
+ * +:through+
1179
+ * +:uniq+
1180
+ * +:validate+
1181
+
1182
+ h6. +:as+
1183
+
1184
+ Setting the +:as+ option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>.
1185
+
1186
+ h6. +:autosave+
1187
+
1188
+ 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.
1189
+
1190
+ h6. +:class_name+
1191
+
1192
+ 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:
1193
+
1194
+ <ruby>
1195
+ class Customer < ActiveRecord::Base
1196
+ has_many :orders, :class_name => "Transaction"
1197
+ end
1198
+ </ruby>
1199
+
1200
+ h6. +:conditions+
1201
+
1202
+ The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
1203
+
1204
+ <ruby>
1205
+ class Customer < ActiveRecord::Base
1206
+ has_many :confirmed_orders, :class_name => "Order",
1207
+ :conditions => "confirmed = 1"
1208
+ end
1209
+ </ruby>
1210
+
1211
+ You can also set conditions via a hash:
1212
+
1213
+ <ruby>
1214
+ class Customer < ActiveRecord::Base
1215
+ has_many :confirmed_orders, :class_name => "Order",
1216
+ :conditions => { :confirmed => true }
1217
+ end
1218
+ </ruby>
1219
+
1220
+ 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+.
1221
+
1222
+ If you need to evaluate conditions dynamically at runtime, you could use string interpolation in single quotes:
1223
+
1224
+ <ruby>
1225
+ class Customer < ActiveRecord::Base
1226
+ has_many :latest_orders, :class_name => "Order",
1227
+ :conditions => 'orders.created_at > #{10.hours.ago.to_s(:db).inspect}'
1228
+ end
1229
+ </ruby>
1230
+
1231
+ Be sure to use single quotes.
1232
+
1233
+ h6. +:counter_sql+
1234
+
1235
+ 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.
1236
+
1237
+ 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.
1238
+
1239
+ h6. +:dependent+
1240
+
1241
+ 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+.
1242
+
1243
+ NOTE: This option is ignored when you use the +:through+ option on the association.
1244
+
1245
+ h6. +:extend+
1246
+
1247
+ 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>.
1248
+
1249
+ h6. +:finder_sql+
1250
+
1251
+ 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.
1252
+
1253
+ h6. +:foreign_key+
1254
+
1255
+ 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:
1256
+
1257
+ <ruby>
1258
+ class Customer < ActiveRecord::Base
1259
+ has_many :orders, :foreign_key => "cust_id"
1260
+ end
1261
+ </ruby>
1262
+
1263
+ TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
1264
+
1265
+ h6. +:group+
1266
+
1267
+ The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
1268
+
1269
+ <ruby>
1270
+ class Customer < ActiveRecord::Base
1271
+ has_many :line_items, :through => :orders, :group => "orders.id"
1272
+ end
1273
+ </ruby>
1274
+
1275
+ h6. +:include+
1276
+
1277
+ 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:
1278
+
1279
+ <ruby>
1280
+ class Customer < ActiveRecord::Base
1281
+ has_many :orders
1282
+ end
1283
+
1284
+ class Order < ActiveRecord::Base
1285
+ belongs_to :customer
1286
+ has_many :line_items
1287
+ end
1288
+
1289
+ class LineItem < ActiveRecord::Base
1290
+ belongs_to :order
1291
+ end
1292
+ </ruby>
1293
+
1294
+ 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:
1295
+
1296
+ <ruby>
1297
+ class Customer < ActiveRecord::Base
1298
+ has_many :orders, :include => :line_items
1299
+ end
1300
+
1301
+ class Order < ActiveRecord::Base
1302
+ belongs_to :customer
1303
+ has_many :line_items
1304
+ end
1305
+
1306
+ class LineItem < ActiveRecord::Base
1307
+ belongs_to :order
1308
+ end
1309
+ </ruby>
1310
+
1311
+ h6. +:limit+
1312
+
1313
+ The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
1314
+
1315
+ <ruby>
1316
+ class Customer < ActiveRecord::Base
1317
+ has_many :recent_orders, :class_name => "Order",
1318
+ :order => "order_date DESC", :limit => 100
1319
+ end
1320
+ </ruby>
1321
+
1322
+ h6. +:offset+
1323
+
1324
+ 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.
1325
+
1326
+ h6. +:order+
1327
+
1328
+ The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
1329
+
1330
+ <ruby>
1331
+ class Customer < ActiveRecord::Base
1332
+ has_many :orders, :order => "date_confirmed DESC"
1333
+ end
1334
+ </ruby>
1335
+
1336
+ h6. +:primary_key+
1337
+
1338
+ 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.
1339
+
1340
+ h6. +:readonly+
1341
+
1342
+ If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
1343
+
1344
+ h6. +:select+
1345
+
1346
+ 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.
1347
+
1348
+ 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.
1349
+
1350
+ h6. +:source+
1351
+
1352
+ 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.
1353
+
1354
+ h6. +:source_type+
1355
+
1356
+ The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
1357
+
1358
+ h6. +:through+
1359
+
1360
+ 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>.
1361
+
1362
+ h6. +:uniq+
1363
+
1364
+ Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
1365
+
1366
+ h6. +:validate+
1367
+
1368
+ 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.
1369
+
1370
+ h5. When are Objects Saved?
1371
+
1372
+ 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.
1373
+
1374
+ If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1375
+
1376
+ 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.
1377
+
1378
+ 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.
1379
+
1380
+ h4. +has_and_belongs_to_many+ Association Reference
1381
+
1382
+ 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.
1383
+
1384
+ h5. Methods Added
1385
+
1386
+ When you declare a +has_and_belongs_to_many+ association, the declaring class automatically gains 13 methods related to the association:
1387
+
1388
+ * <tt><em>collection</em>(force_reload = false)</tt>
1389
+ * <tt><em>collection</em><<(object, ...)</tt>
1390
+ * <tt><em>collection</em>.delete(object, ...)</tt>
1391
+ * <tt><em>collection</em>=objects</tt>
1392
+ * <tt><em>collection_singular</em>_ids</tt>
1393
+ * <tt><em>collection_singular</em>_ids=ids</tt>
1394
+ * <tt><em>collection</em>.clear</tt>
1395
+ * <tt><em>collection</em>.empty?</tt>
1396
+ * <tt><em>collection</em>.size</tt>
1397
+ * <tt><em>collection</em>.find(...)</tt>
1398
+ * <tt><em>collection</em>.exists?(...)</tt>
1399
+ * <tt><em>collection</em>.build(attributes = {})</tt>
1400
+ * <tt><em>collection</em>.create(attributes = {})</tt>
1401
+
1402
+ 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:
1403
+
1404
+ <ruby>
1405
+ class Part < ActiveRecord::Base
1406
+ has_and_belongs_to_many :assemblies
1407
+ end
1408
+ </ruby>
1409
+
1410
+ Each instance of the part model will have these methods:
1411
+
1412
+ <ruby>
1413
+ assemblies(force_reload = false)
1414
+ assemblies<<(object, ...)
1415
+ assemblies.delete(object, ...)
1416
+ assemblies=objects
1417
+ assembly_ids
1418
+ assembly_ids=ids
1419
+ assemblies.clear
1420
+ assemblies.empty?
1421
+ assemblies.size
1422
+ assemblies.find(...)
1423
+ assemblies.exists?(...)
1424
+ assemblies.build(attributes = {}, ...)
1425
+ assemblies.create(attributes = {})
1426
+ </ruby>
1427
+
1428
+ h6. Additional Column Methods
1429
+
1430
+ 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.
1431
+
1432
+ 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+.
1433
+
1434
+
1435
+ h6. <tt><em>collection</em>(force_reload = false)</tt>
1436
+
1437
+ 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.
1438
+
1439
+ <ruby>
1440
+ @assemblies = @part.assemblies
1441
+ </ruby>
1442
+
1443
+ h6. <tt><em>collection</em><<(object, ...)</tt>
1444
+
1445
+ The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by creating records in the join table.
1446
+
1447
+ <ruby>
1448
+ @part.assemblies << @assembly1
1449
+ </ruby>
1450
+
1451
+ NOTE: This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>.
1452
+
1453
+ h6. <tt><em>collection</em>.delete(object, ...)</tt>
1454
+
1455
+ 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.
1456
+
1457
+ <ruby>
1458
+ @part.assemblies.delete(@assembly1)
1459
+ </ruby>
1460
+
1461
+ h6. <tt><em>collection</em>=objects</tt>
1462
+
1463
+ The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
1464
+
1465
+ h6. <tt><em>collection_singular</em>_ids</tt>
1466
+
1467
+ The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.
1468
+
1469
+ <ruby>
1470
+ @assembly_ids = @part.assembly_ids
1471
+ </ruby>
1472
+
1473
+ h6. <tt><em>collection_singular</em>_ids=ids</tt>
1474
+
1475
+ 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.
1476
+
1477
+ h6. <tt><em>collection</em>.clear</tt>
1478
+
1479
+ 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.
1480
+
1481
+ h6. <tt><em>collection</em>.empty?</tt>
1482
+
1483
+ The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.
1484
+
1485
+ <ruby>
1486
+ <% if @part.assemblies.empty? %>
1487
+ This part is not used in any assemblies
1488
+ <% end %>
1489
+ </ruby>
1490
+
1491
+ h6. <tt><em>collection</em>.size</tt>
1492
+
1493
+ The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.
1494
+
1495
+ <ruby>
1496
+ @assembly_count = @part.assemblies.size
1497
+ </ruby>
1498
+
1499
+ h6. <tt><em>collection</em>.find(...)</tt>
1500
+
1501
+ 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.
1502
+
1503
+ <ruby>
1504
+ @new_assemblies = @part.assemblies.find(:all,
1505
+ :conditions => ["created_at > ?", 2.days.ago])
1506
+ </ruby>
1507
+
1508
+ h6. <tt><em>collection</em>.exists?(...)</tt>
1509
+
1510
+ The <tt><em>collection</em>.exists?</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?+.
1511
+
1512
+ h6. <tt><em>collection</em>.build(attributes = {})</tt>
1513
+
1514
+ 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.
1515
+
1516
+ <ruby>
1517
+ @assembly = @part.assemblies.build(
1518
+ {:assembly_name => "Transmission housing"})
1519
+ </ruby>
1520
+
1521
+ h6. <tt><em>collection</em>.create(attributes = {})</tt>
1522
+
1523
+ 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).
1524
+
1525
+ <ruby>
1526
+ @assembly = @part.assemblies.create(
1527
+ {:assembly_name => "Transmission housing"})
1528
+ </ruby>
1529
+
1530
+ h5. Options for +has_and_belongs_to_many+
1531
+
1532
+ 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:
1533
+
1534
+ <ruby>
1535
+ class Parts < ActiveRecord::Base
1536
+ has_and_belongs_to_many :assemblies, :uniq => true,
1537
+ :read_only => true
1538
+ end
1539
+ </ruby>
1540
+
1541
+ The +has_and_belongs_to_many+ association supports these options:
1542
+
1543
+ * +:association_foreign_key+
1544
+ * +:autosave+
1545
+ * +:class_name+
1546
+ * +:conditions+
1547
+ * +:counter_sql+
1548
+ * +:delete_sql+
1549
+ * +:extend+
1550
+ * +:finder_sql+
1551
+ * +:foreign_key+
1552
+ * +:group+
1553
+ * +:include+
1554
+ * +:insert_sql+
1555
+ * +:join_table+
1556
+ * +:limit+
1557
+ * +:offset+
1558
+ * +:order+
1559
+ * +:readonly+
1560
+ * +:select+
1561
+ * +:uniq+
1562
+ * +:validate+
1563
+
1564
+ h6. +:association_foreign_key+
1565
+
1566
+ 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:
1567
+
1568
+ TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when setting up a many-to-many self-join. For example:
1569
+
1570
+ <ruby>
1571
+ class User < ActiveRecord::Base
1572
+ has_and_belongs_to_many :friends, :class_name => "User",
1573
+ :foreign_key => "this_user_id",
1574
+ :association_foreign_key => "other_user_id"
1575
+ end
1576
+ </ruby>
1577
+
1578
+ h6. +:autosave+
1579
+
1580
+ 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.
1581
+
1582
+ h6. +:class_name+
1583
+
1584
+ 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:
1585
+
1586
+ <ruby>
1587
+ class Parts < ActiveRecord::Base
1588
+ has_and_belongs_to_many :assemblies, :class_name => "Gadget"
1589
+ end
1590
+ </ruby>
1591
+
1592
+ h6. +:conditions+
1593
+
1594
+ The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
1595
+
1596
+ <ruby>
1597
+ class Parts < ActiveRecord::Base
1598
+ has_and_belongs_to_many :assemblies,
1599
+ :conditions => "factory = 'Seattle'"
1600
+ end
1601
+ </ruby>
1602
+
1603
+ You can also set conditions via a hash:
1604
+
1605
+ <ruby>
1606
+ class Parts < ActiveRecord::Base
1607
+ has_and_belongs_to_many :assemblies,
1608
+ :conditions => { :factory => 'Seattle' }
1609
+ end
1610
+ </ruby>
1611
+
1612
+ 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".
1613
+
1614
+ h6. +:counter_sql+
1615
+
1616
+ 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.
1617
+
1618
+ 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.
1619
+
1620
+ h6. +:delete_sql+
1621
+
1622
+ 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.
1623
+
1624
+ h6. +:extend+
1625
+
1626
+ 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>.
1627
+
1628
+ h6. +:finder_sql+
1629
+
1630
+ 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.
1631
+
1632
+ h6. +:foreign_key+
1633
+
1634
+ 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:
1635
+
1636
+ <ruby>
1637
+ class User < ActiveRecord::Base
1638
+ has_and_belongs_to_many :friends, :class_name => "User",
1639
+ :foreign_key => "this_user_id",
1640
+ :association_foreign_key => "other_user_id"
1641
+ end
1642
+ </ruby>
1643
+
1644
+ h6. +:group+
1645
+
1646
+ The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
1647
+
1648
+ <ruby>
1649
+ class Parts < ActiveRecord::Base
1650
+ has_and_belongs_to_many :assemblies, :group => "factory"
1651
+ end
1652
+ </ruby>
1653
+
1654
+ h6. +:include+
1655
+
1656
+ You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used.
1657
+
1658
+ h6. +:insert_sql+
1659
+
1660
+ 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.
1661
+
1662
+ h6. +:join_table+
1663
+
1664
+ 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.
1665
+
1666
+ h6. +:limit+
1667
+
1668
+ The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
1669
+
1670
+ <ruby>
1671
+ class Parts < ActiveRecord::Base
1672
+ has_and_belongs_to_many :assemblies, :order => "created_at DESC",
1673
+ :limit => 50
1674
+ end
1675
+ </ruby>
1676
+
1677
+ h6. +:offset+
1678
+
1679
+ 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.
1680
+
1681
+ h6. +:order+
1682
+
1683
+ The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
1684
+
1685
+ <ruby>
1686
+ class Parts < ActiveRecord::Base
1687
+ has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
1688
+ end
1689
+ </ruby>
1690
+
1691
+ h6. +:readonly+
1692
+
1693
+ If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
1694
+
1695
+ h6. +:select+
1696
+
1697
+ 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.
1698
+
1699
+ h6. +:uniq+
1700
+
1701
+ Specify the +:uniq => true+ option to remove duplicates from the collection.
1702
+
1703
+ h6. +:validate+
1704
+
1705
+ 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.
1706
+
1707
+ h5. When are Objects Saved?
1708
+
1709
+ 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.
1710
+
1711
+ If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1712
+
1713
+ 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.
1714
+
1715
+ 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.
1716
+
1717
+ h4. Association Callbacks
1718
+
1719
+ 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.
1720
+
1721
+ 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:
1722
+
1723
+ * +before_add+
1724
+ * +after_add+
1725
+ * +before_remove+
1726
+ * +after_remove+
1727
+
1728
+ You define association callbacks by adding options to the association declaration. For example:
1729
+
1730
+ <ruby>
1731
+ class Customer < ActiveRecord::Base
1732
+ has_many :orders, :before_add => :check_credit_limit
1733
+
1734
+ def check_credit_limit(order)
1735
+ ...
1736
+ end
1737
+ end
1738
+ </ruby>
1739
+
1740
+ Rails passes the object being added or removed to the callback.
1741
+
1742
+ You can stack callbacks on a single event by passing them as an array:
1743
+
1744
+ <ruby>
1745
+ class Customer < ActiveRecord::Base
1746
+ has_many :orders,
1747
+ :before_add => [:check_credit_limit, :calculate_shipping_charges]
1748
+
1749
+ def check_credit_limit(order)
1750
+ ...
1751
+ end
1752
+
1753
+ def calculate_shipping_charges(order)
1754
+ ...
1755
+ end
1756
+ end
1757
+ </ruby>
1758
+
1759
+ 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.
1760
+
1761
+ h4. Association Extensions
1762
+
1763
+ 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:
1764
+
1765
+ <ruby>
1766
+ class Customer < ActiveRecord::Base
1767
+ has_many :orders do
1768
+ def find_by_order_prefix(order_number)
1769
+ find_by_region_id(order_number[0..2])
1770
+ end
1771
+ end
1772
+ end
1773
+ </ruby>
1774
+
1775
+ If you have an extension that should be shared by many associations, you can use a named extension module. For example:
1776
+
1777
+ <ruby>
1778
+ module FindRecentExtension
1779
+ def find_recent
1780
+ find(:all, :conditions => ["created_at > ?", 5.days.ago])
1781
+ end
1782
+ end
1783
+
1784
+ class Customer < ActiveRecord::Base
1785
+ has_many :orders, :extend => FindRecentExtension
1786
+ end
1787
+
1788
+ class Supplier < ActiveRecord::Base
1789
+ has_many :deliveries, :extend => FindRecentExtension
1790
+ end
1791
+ </ruby>
1792
+
1793
+ To include more than one extension module in a single association, specify an array of modules:
1794
+
1795
+ <ruby>
1796
+ class Customer < ActiveRecord::Base
1797
+ has_many :orders,
1798
+ :extend => [FindRecentExtension, FindActiveExtension]
1799
+ end
1800
+ </ruby>
1801
+
1802
+ Extensions can refer to the internals of the association proxy using these three accessors:
1803
+
1804
+ * +proxy_owner+ returns the object that the association is a part of.
1805
+ * +proxy_reflection+ returns the reflection object that describes the association.
1806
+ * +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+.
1807
+
1808
+ h3. Changelog
1809
+
1810
+ "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11
1811
+
1812
+ * April 19, 2009: Added +:touch+ option to +belongs_to+ associations by "Mike Gunderloy":credits.html#mgunderloy
1813
+ * February 1, 2009: Added +:autosave+ option "Mike Gunderloy":credits.html#mgunderloy
1814
+ * September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by "Mike Gunderloy":credits.html#mgunderloy . First release version.
1815
+ * September 22, 2008: Added diagrams, misc. cleanup by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
1816
+ * September 14, 2008: initial version by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)