railties 3.2.22.5 → 4.0.0.beta1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (450) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +186 -78
  3. data/README.rdoc +4 -2
  4. data/lib/rails.rb +11 -44
  5. data/lib/rails/all.rb +0 -1
  6. data/lib/rails/app_rails_loader.rb +37 -0
  7. data/lib/rails/application.rb +176 -124
  8. data/lib/rails/application/bootstrap.rb +29 -23
  9. data/lib/rails/application/configuration.rb +54 -48
  10. data/lib/rails/application/finisher.rb +8 -12
  11. data/lib/rails/application/routes_reloader.rb +2 -2
  12. data/lib/rails/backtrace_cleaner.rb +1 -16
  13. data/lib/rails/cli.rb +2 -2
  14. data/lib/rails/code_statistics.rb +30 -45
  15. data/lib/rails/code_statistics_calculator.rb +79 -0
  16. data/lib/rails/commands.rb +44 -37
  17. data/lib/rails/commands/application.rb +14 -9
  18. data/lib/rails/commands/console.rb +77 -33
  19. data/lib/rails/commands/dbconsole.rb +115 -64
  20. data/lib/rails/commands/destroy.rb +2 -3
  21. data/lib/rails/commands/generate.rb +2 -3
  22. data/lib/rails/commands/plugin_new.rb +0 -2
  23. data/lib/rails/commands/runner.rb +4 -5
  24. data/lib/rails/commands/server.rb +28 -9
  25. data/lib/rails/commands/update.rb +1 -1
  26. data/lib/rails/configuration.rb +35 -8
  27. data/lib/rails/console/app.rb +0 -4
  28. data/lib/rails/deprecation.rb +19 -0
  29. data/lib/rails/engine.rb +111 -92
  30. data/lib/rails/engine/commands.rb +1 -3
  31. data/lib/rails/engine/configuration.rb +26 -19
  32. data/lib/rails/engine/railties.rb +14 -18
  33. data/lib/rails/generators.rb +30 -50
  34. data/lib/rails/generators/actions.rb +38 -103
  35. data/lib/rails/generators/active_model.rb +14 -6
  36. data/lib/rails/generators/app_base.rb +70 -83
  37. data/lib/rails/generators/base.rb +23 -35
  38. data/lib/rails/generators/css/assets/assets_generator.rb +3 -3
  39. data/lib/rails/generators/css/scaffold/scaffold_generator.rb +3 -3
  40. data/lib/rails/generators/erb.rb +2 -2
  41. data/lib/rails/generators/erb/controller/controller_generator.rb +4 -4
  42. data/lib/rails/generators/erb/mailer/mailer_generator.rb +3 -3
  43. data/lib/rails/generators/erb/scaffold/scaffold_generator.rb +4 -4
  44. data/lib/rails/generators/erb/scaffold/templates/index.html.erb +18 -14
  45. data/lib/rails/generators/erb/scaffold/templates/show.html.erb +1 -1
  46. data/lib/rails/generators/generated_attribute.rb +51 -16
  47. data/lib/rails/generators/js/assets/assets_generator.rb +3 -3
  48. data/lib/rails/generators/migration.rb +1 -5
  49. data/lib/rails/generators/named_base.rb +20 -25
  50. data/lib/rails/generators/rails/app/app_generator.rb +40 -48
  51. data/lib/rails/generators/rails/app/templates/Gemfile +8 -7
  52. data/lib/rails/generators/rails/app/templates/README.rdoc +28 -0
  53. data/lib/rails/generators/rails/app/templates/Rakefile +0 -1
  54. data/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt +2 -1
  55. data/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt +5 -0
  56. data/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt +2 -2
  57. data/lib/rails/generators/rails/app/templates/bin/bundle +2 -0
  58. data/lib/rails/generators/rails/app/templates/bin/rails +3 -0
  59. data/lib/rails/generators/rails/app/templates/bin/rake +3 -0
  60. data/lib/rails/generators/rails/app/templates/config/application.rb +5 -43
  61. data/lib/rails/generators/rails/app/templates/config/boot.rb +0 -2
  62. data/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml +2 -2
  63. data/lib/rails/generators/rails/app/templates/config/databases/mysql.yml +1 -4
  64. data/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml +8 -3
  65. data/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml +57 -0
  66. data/lib/rails/generators/rails/app/templates/config/environment.rb +2 -2
  67. data/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt +9 -19
  68. data/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt +40 -29
  69. data/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt +12 -15
  70. data/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb +4 -0
  71. data/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb +6 -5
  72. data/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt +6 -1
  73. data/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt +1 -6
  74. data/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt +6 -6
  75. data/lib/rails/generators/rails/app/templates/config/locales/en.yml +20 -2
  76. data/lib/rails/generators/rails/app/templates/config/routes.rb +15 -24
  77. data/lib/rails/generators/rails/app/templates/db/seeds.rb.tt +2 -2
  78. data/lib/rails/generators/rails/app/templates/gitignore +3 -2
  79. data/lib/rails/generators/rails/app/templates/public/404.html +2 -1
  80. data/lib/rails/generators/rails/app/templates/public/422.html +1 -1
  81. data/lib/rails/generators/rails/app/templates/public/500.html +2 -1
  82. data/lib/rails/generators/rails/app/templates/public/robots.txt +1 -1
  83. data/lib/rails/generators/rails/app/templates/test/test_helper.rb +3 -1
  84. data/lib/rails/generators/rails/assets/assets_generator.rb +5 -5
  85. data/lib/rails/generators/rails/controller/USAGE +7 -7
  86. data/lib/rails/generators/rails/controller/controller_generator.rb +3 -3
  87. data/lib/rails/generators/rails/controller/templates/controller.rb +1 -1
  88. data/lib/rails/generators/rails/generator/generator_generator.rb +4 -4
  89. data/lib/rails/generators/rails/helper/USAGE +1 -1
  90. data/lib/rails/generators/rails/helper/helper_generator.rb +2 -2
  91. data/lib/rails/generators/rails/integration_test/integration_test_generator.rb +2 -2
  92. data/lib/rails/generators/rails/migration/USAGE +12 -6
  93. data/lib/rails/generators/rails/migration/migration_generator.rb +3 -3
  94. data/lib/rails/generators/rails/model/USAGE +53 -4
  95. data/lib/rails/generators/rails/model/model_generator.rb +3 -3
  96. data/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb +81 -39
  97. data/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec +2 -2
  98. data/lib/rails/generators/rails/plugin_new/templates/Gemfile +16 -1
  99. data/lib/rails/generators/rails/plugin_new/templates/Rakefile +3 -9
  100. data/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt +0 -1
  101. data/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt +1 -1
  102. data/lib/rails/generators/rails/plugin_new/templates/{script → bin}/rails.tt +0 -0
  103. data/lib/rails/generators/rails/plugin_new/templates/gitignore +3 -0
  104. data/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb +1 -1
  105. data/lib/rails/generators/rails/plugin_new/templates/rails/application.rb +0 -1
  106. data/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb +0 -1
  107. data/lib/rails/generators/rails/resource/resource_generator.rb +5 -5
  108. data/lib/rails/generators/rails/resource_route/resource_route_generator.rb +2 -2
  109. data/lib/rails/generators/rails/scaffold/scaffold_generator.rb +11 -7
  110. data/lib/rails/generators/rails/scaffold_controller/USAGE +4 -4
  111. data/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb +9 -7
  112. data/lib/rails/generators/rails/scaffold_controller/templates/controller.rb +27 -48
  113. data/lib/rails/generators/rails/task/task_generator.rb +2 -2
  114. data/lib/rails/generators/rails/task/templates/task.rb +1 -1
  115. data/lib/rails/generators/resource_helpers.rb +3 -5
  116. data/lib/rails/generators/test_case.rb +22 -28
  117. data/lib/rails/generators/test_unit.rb +3 -3
  118. data/lib/rails/generators/test_unit/controller/controller_generator.rb +6 -6
  119. data/lib/rails/generators/test_unit/helper/helper_generator.rb +5 -5
  120. data/lib/rails/generators/test_unit/integration/integration_generator.rb +4 -4
  121. data/lib/rails/generators/test_unit/mailer/mailer_generator.rb +6 -6
  122. data/lib/rails/generators/test_unit/model/model_generator.rb +7 -7
  123. data/lib/rails/generators/test_unit/model/templates/fixtures.yml +8 -2
  124. data/lib/rails/generators/test_unit/plugin/plugin_generator.rb +4 -4
  125. data/lib/rails/generators/test_unit/plugin/templates/test_helper.rb +1 -2
  126. data/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb +10 -19
  127. data/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb +5 -5
  128. data/lib/rails/info.rb +3 -3
  129. data/lib/rails/info_controller.rb +26 -8
  130. data/lib/rails/initializable.rb +2 -2
  131. data/lib/rails/paths.rb +59 -54
  132. data/lib/rails/rack/debugger.rb +2 -2
  133. data/lib/rails/rack/logger.rb +33 -8
  134. data/lib/rails/railtie.rb +24 -24
  135. data/lib/rails/railtie/configurable.rb +1 -1
  136. data/lib/rails/railtie/configuration.rb +15 -5
  137. data/lib/rails/ruby_version_check.rb +3 -13
  138. data/lib/rails/rubyprof_ext.rb +1 -1
  139. data/lib/rails/source_annotation_extractor.rb +40 -17
  140. data/lib/rails/tasks/annotations.rake +1 -1
  141. data/lib/rails/tasks/documentation.rake +10 -57
  142. data/lib/rails/tasks/engine.rake +1 -1
  143. data/lib/rails/tasks/framework.rake +9 -9
  144. data/lib/rails/tasks/log.rake +18 -4
  145. data/lib/rails/tasks/middleware.rake +1 -1
  146. data/lib/rails/tasks/misc.rake +2 -9
  147. data/lib/rails/tasks/routes.rake +4 -6
  148. data/lib/rails/tasks/statistics.rake +8 -2
  149. data/lib/rails/tasks/tmp.rake +12 -4
  150. data/lib/rails/templates/layouts/application.html.erb +36 -0
  151. data/lib/rails/templates/rails/info/properties.html.erb +1 -0
  152. data/lib/rails/templates/rails/info/routes.html.erb +9 -0
  153. data/lib/rails/{generators/rails/app/templates/public/index.html → templates/rails/welcome/index.html.erb} +18 -14
  154. data/lib/rails/test_help.rb +6 -29
  155. data/lib/rails/test_unit/railtie.rb +2 -3
  156. data/lib/rails/test_unit/testing.rake +45 -33
  157. data/lib/rails/version.rb +4 -4
  158. data/lib/rails/welcome_controller.rb +7 -0
  159. metadata +86 -378
  160. data/guides/assets/images/belongs_to.png +0 -0
  161. data/guides/assets/images/book_icon.gif +0 -0
  162. data/guides/assets/images/bullet.gif +0 -0
  163. data/guides/assets/images/challenge.png +0 -0
  164. data/guides/assets/images/chapters_icon.gif +0 -0
  165. data/guides/assets/images/check_bullet.gif +0 -0
  166. data/guides/assets/images/credits_pic_blank.gif +0 -0
  167. data/guides/assets/images/csrf.png +0 -0
  168. data/guides/assets/images/customized_error_messages.png +0 -0
  169. data/guides/assets/images/edge_badge.png +0 -0
  170. data/guides/assets/images/error_messages.png +0 -0
  171. data/guides/assets/images/feature_tile.gif +0 -0
  172. data/guides/assets/images/footer_tile.gif +0 -0
  173. data/guides/assets/images/fxn.png +0 -0
  174. data/guides/assets/images/grey_bullet.gif +0 -0
  175. data/guides/assets/images/habtm.png +0 -0
  176. data/guides/assets/images/has_many.png +0 -0
  177. data/guides/assets/images/has_many_through.png +0 -0
  178. data/guides/assets/images/has_one.png +0 -0
  179. data/guides/assets/images/has_one_through.png +0 -0
  180. data/guides/assets/images/header_backdrop.png +0 -0
  181. data/guides/assets/images/header_tile.gif +0 -0
  182. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  183. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  184. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  185. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  186. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  187. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  188. data/guides/assets/images/icons/README +0 -5
  189. data/guides/assets/images/icons/callouts/1.png +0 -0
  190. data/guides/assets/images/icons/callouts/10.png +0 -0
  191. data/guides/assets/images/icons/callouts/11.png +0 -0
  192. data/guides/assets/images/icons/callouts/12.png +0 -0
  193. data/guides/assets/images/icons/callouts/13.png +0 -0
  194. data/guides/assets/images/icons/callouts/14.png +0 -0
  195. data/guides/assets/images/icons/callouts/15.png +0 -0
  196. data/guides/assets/images/icons/callouts/2.png +0 -0
  197. data/guides/assets/images/icons/callouts/3.png +0 -0
  198. data/guides/assets/images/icons/callouts/4.png +0 -0
  199. data/guides/assets/images/icons/callouts/5.png +0 -0
  200. data/guides/assets/images/icons/callouts/6.png +0 -0
  201. data/guides/assets/images/icons/callouts/7.png +0 -0
  202. data/guides/assets/images/icons/callouts/8.png +0 -0
  203. data/guides/assets/images/icons/callouts/9.png +0 -0
  204. data/guides/assets/images/icons/caution.png +0 -0
  205. data/guides/assets/images/icons/example.png +0 -0
  206. data/guides/assets/images/icons/home.png +0 -0
  207. data/guides/assets/images/icons/important.png +0 -0
  208. data/guides/assets/images/icons/next.png +0 -0
  209. data/guides/assets/images/icons/note.png +0 -0
  210. data/guides/assets/images/icons/prev.png +0 -0
  211. data/guides/assets/images/icons/tip.png +0 -0
  212. data/guides/assets/images/icons/up.png +0 -0
  213. data/guides/assets/images/icons/warning.png +0 -0
  214. data/guides/assets/images/jaimeiniesta.jpg +0 -0
  215. data/guides/assets/images/nav_arrow.gif +0 -0
  216. data/guides/assets/images/polymorphic.png +0 -0
  217. data/guides/assets/images/posts_index.png +0 -0
  218. data/guides/assets/images/radar.png +0 -0
  219. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  220. data/guides/assets/images/rails_guides_logo.gif +0 -0
  221. data/guides/assets/images/rails_logo_remix.gif +0 -0
  222. data/guides/assets/images/rails_welcome.png +0 -0
  223. data/guides/assets/images/session_fixation.png +0 -0
  224. data/guides/assets/images/tab_grey.gif +0 -0
  225. data/guides/assets/images/tab_info.gif +0 -0
  226. data/guides/assets/images/tab_note.gif +0 -0
  227. data/guides/assets/images/tab_red.gif +0 -0
  228. data/guides/assets/images/tab_yellow.gif +0 -0
  229. data/guides/assets/images/tab_yellow.png +0 -0
  230. data/guides/assets/images/validation_error_messages.png +0 -0
  231. data/guides/assets/images/vijaydev.jpg +0 -0
  232. data/guides/assets/javascripts/guides.js +0 -7
  233. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  234. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  235. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  236. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  237. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  238. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  239. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  240. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  241. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  242. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  243. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  244. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  245. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  246. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  247. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  248. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  249. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  250. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  251. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  252. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  253. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  254. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  255. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  256. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  257. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  258. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
  259. data/guides/assets/stylesheets/fixes.css +0 -16
  260. data/guides/assets/stylesheets/kindle.css +0 -11
  261. data/guides/assets/stylesheets/main.css +0 -453
  262. data/guides/assets/stylesheets/print.css +0 -52
  263. data/guides/assets/stylesheets/reset.css +0 -43
  264. data/guides/assets/stylesheets/style.css +0 -13
  265. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
  266. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  267. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  268. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  269. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  270. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  271. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  272. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  273. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  274. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  275. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  276. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  277. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  278. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  279. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  280. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  281. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  282. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  283. data/guides/code/getting_started/Gemfile +0 -38
  284. data/guides/code/getting_started/README.rdoc +0 -261
  285. data/guides/code/getting_started/Rakefile +0 -7
  286. data/guides/code/getting_started/app/assets/images/rails.png +0 -0
  287. data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
  288. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
  289. data/guides/code/getting_started/app/assets/javascripts/home.js.coffee +0 -3
  290. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
  291. data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
  292. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
  293. data/guides/code/getting_started/app/assets/stylesheets/home.css.scss +0 -3
  294. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
  295. data/guides/code/getting_started/app/assets/stylesheets/scaffolds.css.scss +0 -56
  296. data/guides/code/getting_started/app/controllers/application_controller.rb +0 -3
  297. data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -16
  298. data/guides/code/getting_started/app/controllers/home_controller.rb +0 -5
  299. data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -84
  300. data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
  301. data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
  302. data/guides/code/getting_started/app/helpers/home_helper.rb +0 -2
  303. data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -5
  304. data/guides/code/getting_started/app/models/comment.rb +0 -3
  305. data/guides/code/getting_started/app/models/post.rb +0 -11
  306. data/guides/code/getting_started/app/models/tag.rb +0 -3
  307. data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
  308. data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
  309. data/guides/code/getting_started/app/views/home/index.html.erb +0 -2
  310. data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
  311. data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -32
  312. data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -6
  313. data/guides/code/getting_started/app/views/posts/index.html.erb +0 -27
  314. data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
  315. data/guides/code/getting_started/app/views/posts/show.html.erb +0 -31
  316. data/guides/code/getting_started/app/views/tags/_form.html.erb +0 -12
  317. data/guides/code/getting_started/config.ru +0 -4
  318. data/guides/code/getting_started/config/application.rb +0 -59
  319. data/guides/code/getting_started/config/boot.rb +0 -6
  320. data/guides/code/getting_started/config/database.yml +0 -25
  321. data/guides/code/getting_started/config/environment.rb +0 -5
  322. data/guides/code/getting_started/config/environments/development.rb +0 -37
  323. data/guides/code/getting_started/config/environments/production.rb +0 -67
  324. data/guides/code/getting_started/config/environments/test.rb +0 -37
  325. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
  326. data/guides/code/getting_started/config/initializers/inflections.rb +0 -15
  327. data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
  328. data/guides/code/getting_started/config/initializers/secret_token.rb +0 -7
  329. data/guides/code/getting_started/config/initializers/session_store.rb +0 -8
  330. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
  331. data/guides/code/getting_started/config/locales/en.yml +0 -5
  332. data/guides/code/getting_started/config/routes.rb +0 -64
  333. data/guides/code/getting_started/db/migrate/20110901012504_create_posts.rb +0 -11
  334. data/guides/code/getting_started/db/migrate/20110901012815_create_comments.rb +0 -12
  335. data/guides/code/getting_started/db/migrate/20110901013701_create_tags.rb +0 -11
  336. data/guides/code/getting_started/db/schema.rb +0 -43
  337. data/guides/code/getting_started/db/seeds.rb +0 -7
  338. data/guides/code/getting_started/doc/README_FOR_APP +0 -2
  339. data/guides/code/getting_started/public/404.html +0 -26
  340. data/guides/code/getting_started/public/422.html +0 -26
  341. data/guides/code/getting_started/public/500.html +0 -25
  342. data/guides/code/getting_started/public/favicon.ico +0 -0
  343. data/guides/code/getting_started/public/robots.txt +0 -5
  344. data/guides/code/getting_started/script/rails +0 -6
  345. data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
  346. data/guides/code/getting_started/test/fixtures/posts.yml +0 -11
  347. data/guides/code/getting_started/test/fixtures/tags.yml +0 -9
  348. data/guides/code/getting_started/test/functional/comments_controller_test.rb +0 -7
  349. data/guides/code/getting_started/test/functional/home_controller_test.rb +0 -9
  350. data/guides/code/getting_started/test/functional/posts_controller_test.rb +0 -49
  351. data/guides/code/getting_started/test/performance/browsing_test.rb +0 -12
  352. data/guides/code/getting_started/test/test_helper.rb +0 -13
  353. data/guides/code/getting_started/test/unit/comment_test.rb +0 -7
  354. data/guides/code/getting_started/test/unit/helpers/comments_helper_test.rb +0 -4
  355. data/guides/code/getting_started/test/unit/helpers/home_helper_test.rb +0 -4
  356. data/guides/code/getting_started/test/unit/helpers/posts_helper_test.rb +0 -4
  357. data/guides/code/getting_started/test/unit/post_test.rb +0 -7
  358. data/guides/code/getting_started/test/unit/tag_test.rb +0 -7
  359. data/guides/rails_guides.rb +0 -50
  360. data/guides/rails_guides/generator.rb +0 -310
  361. data/guides/rails_guides/helpers.rb +0 -45
  362. data/guides/rails_guides/indexer.rb +0 -69
  363. data/guides/rails_guides/levenshtein.rb +0 -31
  364. data/guides/rails_guides/textile_extensions.rb +0 -63
  365. data/guides/source/2_2_release_notes.textile +0 -422
  366. data/guides/source/2_3_release_notes.textile +0 -610
  367. data/guides/source/3_0_release_notes.textile +0 -595
  368. data/guides/source/3_1_release_notes.textile +0 -553
  369. data/guides/source/3_2_release_notes.textile +0 -540
  370. data/guides/source/_license.html.erb +0 -2
  371. data/guides/source/_welcome.html.erb +0 -19
  372. data/guides/source/action_controller_overview.textile +0 -820
  373. data/guides/source/action_mailer_basics.textile +0 -516
  374. data/guides/source/action_view_overview.textile +0 -1497
  375. data/guides/source/active_model_basics.textile +0 -205
  376. data/guides/source/active_record_basics.textile +0 -218
  377. data/guides/source/active_record_querying.textile +0 -1433
  378. data/guides/source/active_record_validations_callbacks.textile +0 -1287
  379. data/guides/source/active_resource_basics.textile +0 -120
  380. data/guides/source/active_support_core_extensions.textile +0 -3715
  381. data/guides/source/api_documentation_guidelines.textile +0 -185
  382. data/guides/source/asset_pipeline.textile +0 -707
  383. data/guides/source/association_basics.textile +0 -1959
  384. data/guides/source/caching_with_rails.textile +0 -437
  385. data/guides/source/command_line.textile +0 -574
  386. data/guides/source/configuring.textile +0 -643
  387. data/guides/source/contributing_to_ruby_on_rails.textile +0 -448
  388. data/guides/source/credits.html.erb +0 -72
  389. data/guides/source/debugging_rails_applications.textile +0 -714
  390. data/guides/source/documents.yaml +0 -157
  391. data/guides/source/engines.textile +0 -618
  392. data/guides/source/form_helpers.textile +0 -798
  393. data/guides/source/generators.textile +0 -621
  394. data/guides/source/getting_started.textile +0 -1931
  395. data/guides/source/i18n.textile +0 -931
  396. data/guides/source/index.html.erb +0 -30
  397. data/guides/source/initialization.textile +0 -1116
  398. data/guides/source/kindle/KINDLE.md +0 -26
  399. data/guides/source/kindle/copyright.html.erb +0 -1
  400. data/guides/source/kindle/layout.html.erb +0 -27
  401. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  402. data/guides/source/kindle/toc.html.erb +0 -24
  403. data/guides/source/kindle/toc.ncx.erb +0 -64
  404. data/guides/source/kindle/welcome.html.erb +0 -5
  405. data/guides/source/layout.html.erb +0 -124
  406. data/guides/source/layouts_and_rendering.textile +0 -1237
  407. data/guides/source/migrations.textile +0 -900
  408. data/guides/source/nested_model_forms.textile +0 -222
  409. data/guides/source/performance_testing.textile +0 -597
  410. data/guides/source/plugins.textile +0 -464
  411. data/guides/source/rails_application_templates.textile +0 -240
  412. data/guides/source/rails_on_rack.textile +0 -236
  413. data/guides/source/routing.textile +0 -885
  414. data/guides/source/ruby_on_rails_guides_guidelines.textile +0 -79
  415. data/guides/source/security.textile +0 -1004
  416. data/guides/source/testing.textile +0 -947
  417. data/guides/w3c_validator.rb +0 -91
  418. data/lib/rails/application/railties.rb +0 -13
  419. data/lib/rails/application/route_inspector.rb +0 -84
  420. data/lib/rails/commands/benchmarker.rb +0 -34
  421. data/lib/rails/commands/plugin.rb +0 -544
  422. data/lib/rails/commands/profiler.rb +0 -33
  423. data/lib/rails/generators/rails/app/templates/README +0 -261
  424. data/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb +0 -3
  425. data/lib/rails/generators/rails/app/templates/app/mailers/.empty_directory +0 -0
  426. data/lib/rails/generators/rails/app/templates/app/models/.empty_directory +0 -0
  427. data/lib/rails/generators/rails/app/templates/doc/README_FOR_APP +0 -2
  428. data/lib/rails/generators/rails/app/templates/public/stylesheets/.empty_directory +0 -0
  429. data/lib/rails/generators/rails/app/templates/script/rails +0 -5
  430. data/lib/rails/generators/rails/app/templates/test/fixtures/.empty_directory +0 -0
  431. data/lib/rails/generators/rails/app/templates/test/functional/.empty_directory +0 -0
  432. data/lib/rails/generators/rails/app/templates/test/integration/.empty_directory +0 -0
  433. data/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb +0 -12
  434. data/lib/rails/generators/rails/app/templates/test/unit/.empty_directory +0 -0
  435. data/lib/rails/generators/rails/generator/templates/templates/.empty_directory +0 -0
  436. data/lib/rails/generators/rails/observer/USAGE +0 -12
  437. data/lib/rails/generators/rails/observer/observer_generator.rb +0 -7
  438. data/lib/rails/generators/rails/performance_test/USAGE +0 -10
  439. data/lib/rails/generators/rails/performance_test/performance_test_generator.rb +0 -7
  440. data/lib/rails/generators/rails/plugin_new/templates/app/mailers/.empty_directory +0 -0
  441. data/lib/rails/generators/rails/plugin_new/templates/app/models/.empty_directory +0 -0
  442. data/lib/rails/generators/rails/session_migration/USAGE +0 -8
  443. data/lib/rails/generators/rails/session_migration/session_migration_generator.rb +0 -8
  444. data/lib/rails/generators/test_unit/observer/observer_generator.rb +0 -13
  445. data/lib/rails/generators/test_unit/observer/templates/unit_test.rb +0 -9
  446. data/lib/rails/generators/test_unit/performance/performance_generator.rb +0 -13
  447. data/lib/rails/generators/test_unit/performance/templates/performance_test.rb +0 -12
  448. data/lib/rails/performance_test_help.rb +0 -3
  449. data/lib/rails/plugin.rb +0 -92
  450. data/lib/rails/script_rails_loader.rb +0 -29
@@ -1,1959 +0,0 @@
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.where(: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 associations:
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 collection of join models can be managed via the API. For example, if you assign
141
-
142
- <ruby>
143
- physician.patients = patients
144
- </ruby>
145
-
146
- new join models are created for newly associated objects, and if some are gone their rows are deleted.
147
-
148
- WARNING: Automatic deletion of join models is direct, no destroy callbacks are triggered.
149
-
150
- 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:
151
-
152
- <ruby>
153
- class Document < ActiveRecord::Base
154
- has_many :sections
155
- has_many :paragraphs, :through => :sections
156
- end
157
-
158
- class Section < ActiveRecord::Base
159
- belongs_to :document
160
- has_many :paragraphs
161
- end
162
-
163
- class Paragraph < ActiveRecord::Base
164
- belongs_to :section
165
- end
166
- </ruby>
167
-
168
- With +:through => :sections+ specified, Rails will now understand:
169
-
170
- <ruby>
171
- @document.paragraphs
172
- </ruby>
173
-
174
- h4. The +has_one :through+ Association
175
-
176
- 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:
177
-
178
- <ruby>
179
- class Supplier < ActiveRecord::Base
180
- has_one :account
181
- has_one :account_history, :through => :account
182
- end
183
-
184
- class Account < ActiveRecord::Base
185
- belongs_to :supplier
186
- has_one :account_history
187
- end
188
-
189
- class AccountHistory < ActiveRecord::Base
190
- belongs_to :account
191
- end
192
- </ruby>
193
-
194
- !images/has_one_through.png(has_one :through Association Diagram)!
195
-
196
- h4. The +has_and_belongs_to_many+ Association
197
-
198
- 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:
199
-
200
- <ruby>
201
- class Assembly < ActiveRecord::Base
202
- has_and_belongs_to_many :parts
203
- end
204
-
205
- class Part < ActiveRecord::Base
206
- has_and_belongs_to_many :assemblies
207
- end
208
- </ruby>
209
-
210
- !images/habtm.png(has_and_belongs_to_many Association Diagram)!
211
-
212
- h4. Choosing Between +belongs_to+ and +has_one+
213
-
214
- If you want to set up a one-to-one 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?
215
-
216
- 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:
217
-
218
- <ruby>
219
- class Supplier < ActiveRecord::Base
220
- has_one :account
221
- end
222
-
223
- class Account < ActiveRecord::Base
224
- belongs_to :supplier
225
- end
226
- </ruby>
227
-
228
- The corresponding migration might look like this:
229
-
230
- <ruby>
231
- class CreateSuppliers < ActiveRecord::Migration
232
- def change
233
- create_table :suppliers do |t|
234
- t.string :name
235
- t.timestamps
236
- end
237
-
238
- create_table :accounts do |t|
239
- t.integer :supplier_id
240
- t.string :account_number
241
- t.timestamps
242
- end
243
- end
244
- end
245
- </ruby>
246
-
247
- 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.
248
-
249
- h4. Choosing Between +has_many :through+ and +has_and_belongs_to_many+
250
-
251
- 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:
252
-
253
- <ruby>
254
- class Assembly < ActiveRecord::Base
255
- has_and_belongs_to_many :parts
256
- end
257
-
258
- class Part < ActiveRecord::Base
259
- has_and_belongs_to_many :assemblies
260
- end
261
- </ruby>
262
-
263
- 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:
264
-
265
- <ruby>
266
- class Assembly < ActiveRecord::Base
267
- has_many :manifests
268
- has_many :parts, :through => :manifests
269
- end
270
-
271
- class Manifest < ActiveRecord::Base
272
- belongs_to :assembly
273
- belongs_to :part
274
- end
275
-
276
- class Part < ActiveRecord::Base
277
- has_many :manifests
278
- has_many :assemblies, :through => :manifests
279
- end
280
- </ruby>
281
-
282
- 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).
283
-
284
- You should use +has_many :through+ if you need validations, callbacks, or extra attributes on the join model.
285
-
286
- h4. Polymorphic Associations
287
-
288
- 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:
289
-
290
- <ruby>
291
- class Picture < ActiveRecord::Base
292
- belongs_to :imageable, :polymorphic => true
293
- end
294
-
295
- class Employee < ActiveRecord::Base
296
- has_many :pictures, :as => :imageable
297
- end
298
-
299
- class Product < ActiveRecord::Base
300
- has_many :pictures, :as => :imageable
301
- end
302
- </ruby>
303
-
304
- 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+.
305
-
306
- Similarly, you can retrieve +@product.pictures+.
307
-
308
- 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:
309
-
310
- <ruby>
311
- class CreatePictures < ActiveRecord::Migration
312
- def change
313
- create_table :pictures do |t|
314
- t.string :name
315
- t.integer :imageable_id
316
- t.string :imageable_type
317
- t.timestamps
318
- end
319
- end
320
- end
321
- </ruby>
322
-
323
- This migration can be simplified by using the +t.references+ form:
324
-
325
- <ruby>
326
- class CreatePictures < ActiveRecord::Migration
327
- def change
328
- create_table :pictures do |t|
329
- t.string :name
330
- t.references :imageable, :polymorphic => true
331
- t.timestamps
332
- end
333
- end
334
- end
335
- </ruby>
336
-
337
- !images/polymorphic.png(Polymorphic Association Diagram)!
338
-
339
- h4. Self Joins
340
-
341
- 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:
342
-
343
- <ruby>
344
- class Employee < ActiveRecord::Base
345
- has_many :subordinates, :class_name => "Employee",
346
- :foreign_key => "manager_id"
347
- belongs_to :manager, :class_name => "Employee"
348
- end
349
- </ruby>
350
-
351
- With this setup, you can retrieve +@employee.subordinates+ and +@employee.manager+.
352
-
353
- h3. Tips, Tricks, and Warnings
354
-
355
- Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
356
-
357
- * Controlling caching
358
- * Avoiding name collisions
359
- * Updating the schema
360
- * Controlling association scope
361
- * Bi-directional associations
362
-
363
- h4. Controlling Caching
364
-
365
- 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:
366
-
367
- <ruby>
368
- customer.orders # retrieves orders from the database
369
- customer.orders.size # uses the cached copy of orders
370
- customer.orders.empty? # uses the cached copy of orders
371
- </ruby>
372
-
373
- 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:
374
-
375
- <ruby>
376
- customer.orders # retrieves orders from the database
377
- customer.orders.size # uses the cached copy of orders
378
- customer.orders(true).empty? # discards the cached copy of orders
379
- # and goes back to the database
380
- </ruby>
381
-
382
- h4. Avoiding Name Collisions
383
-
384
- 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.
385
-
386
- h4. Updating the Schema
387
-
388
- 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.
389
-
390
- h5. Creating Foreign Keys for +belongs_to+ Associations
391
-
392
- When you declare a +belongs_to+ association, you need to create foreign keys as appropriate. For example, consider this model:
393
-
394
- <ruby>
395
- class Order < ActiveRecord::Base
396
- belongs_to :customer
397
- end
398
- </ruby>
399
-
400
- This declaration needs to be backed up by the proper foreign key declaration on the orders table:
401
-
402
- <ruby>
403
- class CreateOrders < ActiveRecord::Migration
404
- def change
405
- create_table :orders do |t|
406
- t.datetime :order_date
407
- t.string :order_number
408
- t.integer :customer_id
409
- end
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 +&lt;+ 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 change
439
- create_table :assemblies_parts, :id => false do |t|
440
- t.integer :assembly_id
441
- t.integer :part_id
442
- end
443
- end
444
- end
445
- </ruby>
446
-
447
- 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 behavior in a +has_and_belongs_to_many+ association like mangled models IDs, or exceptions about conflicting IDs chances are you forgot that bit.
448
-
449
- h4. Controlling Association Scope
450
-
451
- 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:
452
-
453
- <ruby>
454
- module MyApplication
455
- module Business
456
- class Supplier < ActiveRecord::Base
457
- has_one :account
458
- end
459
-
460
- class Account < ActiveRecord::Base
461
- belongs_to :supplier
462
- end
463
- end
464
- end
465
- </ruby>
466
-
467
- 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:
468
-
469
- <ruby>
470
- module MyApplication
471
- module Business
472
- class Supplier < ActiveRecord::Base
473
- has_one :account
474
- end
475
- end
476
-
477
- module Billing
478
- class Account < ActiveRecord::Base
479
- belongs_to :supplier
480
- end
481
- end
482
- end
483
- </ruby>
484
-
485
- To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:
486
-
487
- <ruby>
488
- module MyApplication
489
- module Business
490
- class Supplier < ActiveRecord::Base
491
- has_one :account,
492
- :class_name => "MyApplication::Billing::Account"
493
- end
494
- end
495
-
496
- module Billing
497
- class Account < ActiveRecord::Base
498
- belongs_to :supplier,
499
- :class_name => "MyApplication::Business::Supplier"
500
- end
501
- end
502
- end
503
- </ruby>
504
-
505
- h4. Bi-directional Associations
506
-
507
- It's normal for associations to work in two directions, requiring declaration on two different models:
508
-
509
- <ruby>
510
- class Customer < ActiveRecord::Base
511
- has_many :orders
512
- end
513
-
514
- class Order < ActiveRecord::Base
515
- belongs_to :customer
516
- end
517
- </ruby>
518
-
519
- By default, Active Record doesn't know about the connection between these associations. This can lead to two copies of an object getting out of sync:
520
-
521
- <ruby>
522
- c = Customer.first
523
- o = c.orders.first
524
- c.first_name == o.customer.first_name # => true
525
- c.first_name = 'Manny'
526
- c.first_name == o.customer.first_name # => false
527
- </ruby>
528
-
529
- This happens because c and o.customer are two different in-memory representations of the same data, and neither one is automatically refreshed from changes to the other. Active Record provides the +:inverse_of+ option so that you can inform it of these relations:
530
-
531
- <ruby>
532
- class Customer < ActiveRecord::Base
533
- has_many :orders, :inverse_of => :customer
534
- end
535
-
536
- class Order < ActiveRecord::Base
537
- belongs_to :customer, :inverse_of => :orders
538
- end
539
- </ruby>
540
-
541
- With these changes, Active Record will only load one copy of the customer object, preventing inconsistencies and making your application more efficient:
542
-
543
- <ruby>
544
- c = Customer.first
545
- o = c.orders.first
546
- c.first_name == o.customer.first_name # => true
547
- c.first_name = 'Manny'
548
- c.first_name == o.customer.first_name # => true
549
- </ruby>
550
-
551
- There are a few limitations to +inverse_of+ support:
552
-
553
- * They do not work with <tt>:through</tt> associations.
554
- * They do not work with <tt>:polymorphic</tt> associations.
555
- * They do not work with <tt>:as</tt> associations.
556
- * For +belongs_to+ associations, +has_many+ inverse associations are ignored.
557
-
558
- h3. Detailed Association Reference
559
-
560
- 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.
561
-
562
- h4. +belongs_to+ Association Reference
563
-
564
- 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.
565
-
566
- h5. Methods Added by +belongs_to+
567
-
568
- When you declare a +belongs_to+ association, the declaring class automatically gains four methods related to the association:
569
-
570
- * <tt><em>association</em>(force_reload = false)</tt>
571
- * <tt><em>association</em>=(associate)</tt>
572
- * <tt>build_<em>association</em>(attributes = {})</tt>
573
- * <tt>create_<em>association</em>(attributes = {})</tt>
574
-
575
- 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:
576
-
577
- <ruby>
578
- class Order < ActiveRecord::Base
579
- belongs_to :customer
580
- end
581
- </ruby>
582
-
583
- Each instance of the order model will have these methods:
584
-
585
- <ruby>
586
- customer
587
- customer=
588
- build_customer
589
- create_customer
590
- </ruby>
591
-
592
- NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix.
593
-
594
- h6(#belongs_to-association). <tt><em>association</em>(force_reload = false)</tt>
595
-
596
- The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.
597
-
598
- <ruby>
599
- @customer = @order.customer
600
- </ruby>
601
-
602
- 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.
603
-
604
- h6(#belongs_to-association_equal). <tt>_association_=(associate)</tt>
605
-
606
- 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.
607
-
608
- <ruby>
609
- @order.customer = @customer
610
- </ruby>
611
-
612
- h6(#belongs_to-build_association). <tt>build_<em>association</em>(attributes = {})</tt>
613
-
614
- 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.
615
-
616
- <ruby>
617
- @customer = @order.build_customer(:customer_number => 123,
618
- :customer_name => "John Doe")
619
- </ruby>
620
-
621
- h6(#belongs_to-create_association). <tt>create_<em>association</em>(attributes = {})</tt>
622
-
623
- 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, the link through this object's foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
624
-
625
- <ruby>
626
- @customer = @order.create_customer(:customer_number => 123,
627
- :customer_name => "John Doe")
628
- </ruby>
629
-
630
-
631
- h5. Options for +belongs_to+
632
-
633
- While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +belongs_to+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
634
-
635
- <ruby>
636
- class Order < ActiveRecord::Base
637
- belongs_to :customer, :counter_cache => true,
638
- :conditions => "active = 1"
639
- end
640
- </ruby>
641
-
642
- The +belongs_to+ association supports these options:
643
-
644
- * +:autosave+
645
- * +:class_name+
646
- * +:conditions+
647
- * +:counter_cache+
648
- * +:dependent+
649
- * +:foreign_key+
650
- * +:include+
651
- * +:inverse_of+
652
- * +:polymorphic+
653
- * +:readonly+
654
- * +:select+
655
- * +:touch+
656
- * +:validate+
657
-
658
- h6(#belongs_to-autosave). +:autosave+
659
-
660
- 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.
661
-
662
- h6(#belongs_to-class_name). +:class_name+
663
-
664
- 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:
665
-
666
- <ruby>
667
- class Order < ActiveRecord::Base
668
- belongs_to :customer, :class_name => "Patron"
669
- end
670
- </ruby>
671
-
672
- h6(#belongs_to-conditions). +:conditions+
673
-
674
- The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
675
-
676
- <ruby>
677
- class Order < ActiveRecord::Base
678
- belongs_to :customer, :conditions => "active = 1"
679
- end
680
- </ruby>
681
-
682
- h6(#belongs_to-counter_cache). +:counter_cache+
683
-
684
- The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
685
-
686
- <ruby>
687
- class Order < ActiveRecord::Base
688
- belongs_to :customer
689
- end
690
- class Customer < ActiveRecord::Base
691
- has_many :orders
692
- end
693
- </ruby>
694
-
695
- 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:
696
-
697
- <ruby>
698
- class Order < ActiveRecord::Base
699
- belongs_to :customer, :counter_cache => true
700
- end
701
- class Customer < ActiveRecord::Base
702
- has_many :orders
703
- end
704
- </ruby>
705
-
706
- With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +size+ method.
707
-
708
- 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:
709
-
710
- <ruby>
711
- class Order < ActiveRecord::Base
712
- belongs_to :customer, :counter_cache => :count_of_orders
713
- end
714
- class Customer < ActiveRecord::Base
715
- has_many :orders
716
- end
717
- </ruby>
718
-
719
- Counter cache columns are added to the containing model's list of read-only attributes through +attr_readonly+.
720
-
721
- h6(#belongs_to-dependent). +:dependent+
722
-
723
- 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.
724
-
725
- 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.
726
-
727
- h6(#belongs_to-foreign_key). +:foreign_key+
728
-
729
- By convention, Rails assumes 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:
730
-
731
- <ruby>
732
- class Order < ActiveRecord::Base
733
- belongs_to :customer, :class_name => "Patron",
734
- :foreign_key => "patron_id"
735
- end
736
- </ruby>
737
-
738
- TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
739
-
740
- h6(#belongs_to-includes). +:include+
741
-
742
- 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:
743
-
744
- <ruby>
745
- class LineItem < ActiveRecord::Base
746
- belongs_to :order
747
- end
748
-
749
- class Order < ActiveRecord::Base
750
- belongs_to :customer
751
- has_many :line_items
752
- end
753
-
754
- class Customer < ActiveRecord::Base
755
- has_many :orders
756
- end
757
- </ruby>
758
-
759
- 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:
760
-
761
- <ruby>
762
- class LineItem < ActiveRecord::Base
763
- belongs_to :order, :include => :customer
764
- end
765
-
766
- class Order < ActiveRecord::Base
767
- belongs_to :customer
768
- has_many :line_items
769
- end
770
-
771
- class Customer < ActiveRecord::Base
772
- has_many :orders
773
- end
774
- </ruby>
775
-
776
- 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.
777
-
778
- h6(#belongs_to-inverse_of). +:inverse_of+
779
-
780
- The +:inverse_of+ option specifies the name of the +has_many+ or +has_one+ association that is the inverse of this association. Does not work in combination with the +:polymorphic+ options.
781
-
782
- <ruby>
783
- class Customer < ActiveRecord::Base
784
- has_many :orders, :inverse_of => :customer
785
- end
786
-
787
- class Order < ActiveRecord::Base
788
- belongs_to :customer, :inverse_of => :orders
789
- end
790
- </ruby>
791
-
792
- h6(#belongs_to-polymorphic). +:polymorphic+
793
-
794
- 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>.
795
-
796
- h6(#belongs_to-readonly). +:readonly+
797
-
798
- If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
799
-
800
- h6(#belongs_to-select). +:select+
801
-
802
- 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.
803
-
804
- 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.
805
-
806
- h6(#belongs_to-touch). +:touch+
807
-
808
- 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:
809
-
810
- <ruby>
811
- class Order < ActiveRecord::Base
812
- belongs_to :customer, :touch => true
813
- end
814
-
815
- class Customer < ActiveRecord::Base
816
- has_many :orders
817
- end
818
- </ruby>
819
-
820
- 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:
821
-
822
- <ruby>
823
- class Order < ActiveRecord::Base
824
- belongs_to :customer, :touch => :orders_updated_at
825
- end
826
- </ruby>
827
-
828
- h6(#belongs_to-validate). +:validate+
829
-
830
- 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.
831
-
832
- h5(#belongs_to-do_any_associated_objects_exist). Do Any Associated Objects Exist?
833
-
834
- You can see if any associated objects exist by using the <tt><em>association</em>.nil?</tt> method:
835
-
836
- <ruby>
837
- if @order.customer.nil?
838
- @msg = "No customer found for this order"
839
- end
840
- </ruby>
841
-
842
- h5(#belongs_to-when_are_objects_saved). When are Objects Saved?
843
-
844
- Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either.
845
-
846
- h4. +has_one+ Association Reference
847
-
848
- 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.
849
-
850
- h5. Methods Added by +has_one+
851
-
852
- When you declare a +has_one+ association, the declaring class automatically gains four methods related to the association:
853
-
854
- * <tt><em>association</em>(force_reload = false)</tt>
855
- * <tt><em>association</em>=(associate)</tt>
856
- * <tt>build_<em>association</em>(attributes = {})</tt>
857
- * <tt>create_<em>association</em>(attributes = {})</tt>
858
-
859
- 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:
860
-
861
- <ruby>
862
- class Supplier < ActiveRecord::Base
863
- has_one :account
864
- end
865
- </ruby>
866
-
867
- Each instance of the +Supplier+ model will have these methods:
868
-
869
- <ruby>
870
- account
871
- account=
872
- build_account
873
- create_account
874
- </ruby>
875
-
876
- NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix.
877
-
878
- h6(#has_one-association). <tt><em>association</em>(force_reload = false)</tt>
879
-
880
- The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.
881
-
882
- <ruby>
883
- @account = @supplier.account
884
- </ruby>
885
-
886
- 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.
887
-
888
- h6(#has_one-association_equal). <tt><em>association</em>=(associate)</tt>
889
-
890
- 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.
891
-
892
- <ruby>
893
- @supplier.account = @account
894
- </ruby>
895
-
896
- h6(#has_one-build_association). <tt>build_<em>association</em>(attributes = {})</tt>
897
-
898
- 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.
899
-
900
- <ruby>
901
- @account = @supplier.build_account(:terms => "Net 30")
902
- </ruby>
903
-
904
- h6(#has_one-create_association). <tt>create_<em>association</em>(attributes = {})</tt>
905
-
906
- 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, the link through its foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
907
-
908
- <ruby>
909
- @account = @supplier.create_account(:terms => "Net 30")
910
- </ruby>
911
-
912
- h5. Options for +has_one+
913
-
914
- While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +has_one+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
915
-
916
- <ruby>
917
- class Supplier < ActiveRecord::Base
918
- has_one :account, :class_name => "Billing", :dependent => :nullify
919
- end
920
- </ruby>
921
-
922
- The +has_one+ association supports these options:
923
-
924
- * +:as+
925
- * +:autosave+
926
- * +:class_name+
927
- * +:conditions+
928
- * +:dependent+
929
- * +:foreign_key+
930
- * +:include+
931
- * +:inverse_of+
932
- * +:order+
933
- * +:primary_key+
934
- * +:readonly+
935
- * +:select+
936
- * +:source+
937
- * +:source_type+
938
- * +:through+
939
- * +:validate+
940
-
941
- h6(#has_one-as). +:as+
942
-
943
- 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>.
944
-
945
- h6(#has_one-autosave). +:autosave+
946
-
947
- 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.
948
-
949
- h6(#has_one-class_name). +:class_name+
950
-
951
- 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:
952
-
953
- <ruby>
954
- class Supplier < ActiveRecord::Base
955
- has_one :account, :class_name => "Billing"
956
- end
957
- </ruby>
958
-
959
- h6(#has_one-conditions). +:conditions+
960
-
961
- The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
962
-
963
- <ruby>
964
- class Supplier < ActiveRecord::Base
965
- has_one :account, :conditions => "confirmed = 1"
966
- end
967
- </ruby>
968
-
969
- h6(#has_one-dependent). +:dependent+
970
-
971
- 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+.
972
-
973
- h6(#has_one-foreign_key). +:foreign_key+
974
-
975
- By convention, Rails assumes 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:
976
-
977
- <ruby>
978
- class Supplier < ActiveRecord::Base
979
- has_one :account, :foreign_key => "supp_id"
980
- end
981
- </ruby>
982
-
983
- TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
984
-
985
- h6(#has_one-include). +:include+
986
-
987
- 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:
988
-
989
- <ruby>
990
- class Supplier < ActiveRecord::Base
991
- has_one :account
992
- end
993
-
994
- class Account < ActiveRecord::Base
995
- belongs_to :supplier
996
- belongs_to :representative
997
- end
998
-
999
- class Representative < ActiveRecord::Base
1000
- has_many :accounts
1001
- end
1002
- </ruby>
1003
-
1004
- 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:
1005
-
1006
- <ruby>
1007
- class Supplier < ActiveRecord::Base
1008
- has_one :account, :include => :representative
1009
- end
1010
-
1011
- class Account < ActiveRecord::Base
1012
- belongs_to :supplier
1013
- belongs_to :representative
1014
- end
1015
-
1016
- class Representative < ActiveRecord::Base
1017
- has_many :accounts
1018
- end
1019
- </ruby>
1020
-
1021
- h6(#has_one-inverse_of). +:inverse_of+
1022
-
1023
- The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options.
1024
-
1025
- <ruby>
1026
- class Supplier < ActiveRecord::Base
1027
- has_one :account, :inverse_of => :supplier
1028
- end
1029
-
1030
- class Account < ActiveRecord::Base
1031
- belongs_to :supplier, :inverse_of => :account
1032
- end
1033
- </ruby>
1034
-
1035
- h6(#has_one-order). +:order+
1036
-
1037
- The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
1038
-
1039
- h6(#has_one-primary_key). +:primary_key+
1040
-
1041
- By convention, Rails assumes 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.
1042
-
1043
- h6(#has_one-readonly). +:readonly+
1044
-
1045
- If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
1046
-
1047
- h6(#has_one-select). +:select+
1048
-
1049
- 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.
1050
-
1051
- h6(#has_one-source). +:source+
1052
-
1053
- The +:source+ option specifies the source association name for a +has_one :through+ association.
1054
-
1055
- h6(#has_one-source_type). +:source_type+
1056
-
1057
- The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
1058
-
1059
- h6(#has_one-through). +:through+
1060
-
1061
- 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>.
1062
-
1063
- h6(#has_one-validate). +:validate+
1064
-
1065
- 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.
1066
-
1067
- h5(#has_one-do_any_associated_objects_exist). Do Any Associated Objects Exist?
1068
-
1069
- You can see if any associated objects exist by using the <tt><em>association</em>.nil?</tt> method:
1070
-
1071
- <ruby>
1072
- if @supplier.account.nil?
1073
- @msg = "No account found for this supplier"
1074
- end
1075
- </ruby>
1076
-
1077
- h5(#has_one-when_are_objects_saved). When are Objects Saved?
1078
-
1079
- 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.
1080
-
1081
- If either of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1082
-
1083
- 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.
1084
-
1085
- 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.
1086
-
1087
- h4. +has_many+ Association Reference
1088
-
1089
- 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.
1090
-
1091
- h5. Methods Added by +has_many+
1092
-
1093
- When you declare a +has_many+ association, the declaring class automatically gains 13 methods related to the association:
1094
-
1095
- * <tt><em>collection</em>(force_reload = false)</tt>
1096
- * <tt><em>collection</em><<(object, ...)</tt>
1097
- * <tt><em>collection</em>.delete(object, ...)</tt>
1098
- * <tt><em>collection</em>=objects</tt>
1099
- * <tt><em>collection_singular</em>_ids</tt>
1100
- * <tt><em>collection_singular</em>_ids=ids</tt>
1101
- * <tt><em>collection</em>.clear</tt>
1102
- * <tt><em>collection</em>.empty?</tt>
1103
- * <tt><em>collection</em>.size</tt>
1104
- * <tt><em>collection</em>.find(...)</tt>
1105
- * <tt><em>collection</em>.where(...)</tt>
1106
- * <tt><em>collection</em>.exists?(...)</tt>
1107
- * <tt><em>collection</em>.build(attributes = {}, ...)</tt>
1108
- * <tt><em>collection</em>.create(attributes = {})</tt>
1109
-
1110
- 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:
1111
-
1112
- <ruby>
1113
- class Customer < ActiveRecord::Base
1114
- has_many :orders
1115
- end
1116
- </ruby>
1117
-
1118
- Each instance of the customer model will have these methods:
1119
-
1120
- <ruby>
1121
- orders(force_reload = false)
1122
- orders<<(object, ...)
1123
- orders.delete(object, ...)
1124
- orders=objects
1125
- order_ids
1126
- order_ids=ids
1127
- orders.clear
1128
- orders.empty?
1129
- orders.size
1130
- orders.find(...)
1131
- orders.where(...)
1132
- orders.exists?(...)
1133
- orders.build(attributes = {}, ...)
1134
- orders.create(attributes = {})
1135
- </ruby>
1136
-
1137
- h6(#has_many-collection). <tt><em>collection</em>(force_reload = false)</tt>
1138
-
1139
- 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.
1140
-
1141
- <ruby>
1142
- @orders = @customer.orders
1143
- </ruby>
1144
-
1145
- h6(#has_many-collection-lt_lt). <tt><em>collection</em><<(object, ...)</tt>
1146
-
1147
- 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.
1148
-
1149
- <ruby>
1150
- @customer.orders << @order1
1151
- </ruby>
1152
-
1153
- h6(#has_many-collection-delete). <tt><em>collection</em>.delete(object, ...)</tt>
1154
-
1155
- The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by setting their foreign keys to +NULL+.
1156
-
1157
- <ruby>
1158
- @customer.orders.delete(@order1)
1159
- </ruby>
1160
-
1161
- WARNING: Additionally, objects will be destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+.
1162
-
1163
-
1164
- h6(#has_many-collection-equal). <tt><em>collection</em>=objects</tt>
1165
-
1166
- The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
1167
-
1168
- h6(#has_many-collection_singular). <tt><em>collection_singular</em>_ids</tt>
1169
-
1170
- The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.
1171
-
1172
- <ruby>
1173
- @order_ids = @customer.order_ids
1174
- </ruby>
1175
-
1176
- h6(#has_many-collection_singular_ids_ids). <tt><em>collection_singular</em>_ids=ids</tt>
1177
-
1178
- 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.
1179
-
1180
- h6(#has_many-collection-clear). <tt><em>collection</em>.clear</tt>
1181
-
1182
- 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+.
1183
-
1184
- h6(#has_many-collection-empty). <tt><em>collection</em>.empty?</tt>
1185
-
1186
- The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.
1187
-
1188
- <ruby>
1189
- <% if @customer.orders.empty? %>
1190
- No Orders Found
1191
- <% end %>
1192
- </ruby>
1193
-
1194
- h6(#has_many-collection-size). <tt><em>collection</em>.size</tt>
1195
-
1196
- The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.
1197
-
1198
- <ruby>
1199
- @order_count = @customer.orders.size
1200
- </ruby>
1201
-
1202
- h6(#has_many-collection-find). <tt><em>collection</em>.find(...)</tt>
1203
-
1204
- The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
1205
-
1206
- <ruby>
1207
- @open_orders = @customer.orders.where(:open => 1)
1208
- </ruby>
1209
-
1210
- h6(#has_many-collection-where). <tt><em>collection</em>.where(...)</tt>
1211
-
1212
- The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.
1213
-
1214
- <ruby>
1215
- @open_orders = @customer.orders.where(:open => true) # No query yet
1216
- @open_order = @open_orders.first # Now the database will be queried
1217
- </ruby>
1218
-
1219
- h6(#has_many-collection-exists). <tt><em>collection</em>.exists?(...)</tt>
1220
-
1221
- 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?+.
1222
-
1223
- h6(#has_many-collection-build). <tt><em>collection</em>.build(attributes = {}, ...)</tt>
1224
-
1225
- 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.
1226
-
1227
- <ruby>
1228
- @order = @customer.orders.build(:order_date => Time.now,
1229
- :order_number => "A12345")
1230
- </ruby>
1231
-
1232
- h6(#has_many-collection-create). <tt><em>collection</em>.create(attributes = {})</tt>
1233
-
1234
- 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, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
1235
-
1236
- <ruby>
1237
- @order = @customer.orders.create(:order_date => Time.now,
1238
- :order_number => "A12345")
1239
- </ruby>
1240
-
1241
- h5. Options for +has_many+
1242
-
1243
- While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +has_many+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
1244
-
1245
- <ruby>
1246
- class Customer < ActiveRecord::Base
1247
- has_many :orders, :dependent => :delete_all, :validate => :false
1248
- end
1249
- </ruby>
1250
-
1251
- The +has_many+ association supports these options:
1252
-
1253
- * +:as+
1254
- * +:autosave+
1255
- * +:class_name+
1256
- * +:conditions+
1257
- * +:counter_sql+
1258
- * +:dependent+
1259
- * +:extend+
1260
- * +:finder_sql+
1261
- * +:foreign_key+
1262
- * +:group+
1263
- * +:include+
1264
- * +:inverse_of+
1265
- * +:limit+
1266
- * +:offset+
1267
- * +:order+
1268
- * +:primary_key+
1269
- * +:readonly+
1270
- * +:select+
1271
- * +:source+
1272
- * +:source_type+
1273
- * +:through+
1274
- * +:uniq+
1275
- * +:validate+
1276
-
1277
- h6(#has_many-as). +:as+
1278
-
1279
- Setting the +:as+ option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>.
1280
-
1281
- h6(#has_many-autosave). +:autosave+
1282
-
1283
- 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.
1284
-
1285
- h6(#has_many-class_name). +:class_name+
1286
-
1287
- 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:
1288
-
1289
- <ruby>
1290
- class Customer < ActiveRecord::Base
1291
- has_many :orders, :class_name => "Transaction"
1292
- end
1293
- </ruby>
1294
-
1295
- h6(#has_many-conditions). +:conditions+
1296
-
1297
- The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
1298
-
1299
- <ruby>
1300
- class Customer < ActiveRecord::Base
1301
- has_many :confirmed_orders, :class_name => "Order",
1302
- :conditions => "confirmed = 1"
1303
- end
1304
- </ruby>
1305
-
1306
- You can also set conditions via a hash:
1307
-
1308
- <ruby>
1309
- class Customer < ActiveRecord::Base
1310
- has_many :confirmed_orders, :class_name => "Order",
1311
- :conditions => { :confirmed => true }
1312
- end
1313
- </ruby>
1314
-
1315
- 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+.
1316
-
1317
- If you need to evaluate conditions dynamically at runtime, use a proc:
1318
-
1319
- <ruby>
1320
- class Customer < ActiveRecord::Base
1321
- has_many :latest_orders, :class_name => "Order",
1322
- :conditions => proc { ["orders.created_at > ?", 10.hours.ago] }
1323
- end
1324
- </ruby>
1325
-
1326
- h6(#has_many-counter_sql). +:counter_sql+
1327
-
1328
- 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.
1329
-
1330
- 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.
1331
-
1332
- h6(#has_many-dependent). +:dependent+
1333
-
1334
- 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+.
1335
-
1336
- NOTE: This option is ignored when you use the +:through+ option on the association.
1337
-
1338
- h6(#has_many-extend). +:extend+
1339
-
1340
- 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>.
1341
-
1342
- h6(#has_many-finder_sql). +:finder_sql+
1343
-
1344
- 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.
1345
-
1346
- h6(#has_many-foreign_key). +:foreign_key+
1347
-
1348
- By convention, Rails assumes 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:
1349
-
1350
- <ruby>
1351
- class Customer < ActiveRecord::Base
1352
- has_many :orders, :foreign_key => "cust_id"
1353
- end
1354
- </ruby>
1355
-
1356
- TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
1357
-
1358
- h6(#has_many-group). +:group+
1359
-
1360
- The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
1361
-
1362
- <ruby>
1363
- class Customer < ActiveRecord::Base
1364
- has_many :line_items, :through => :orders, :group => "orders.id"
1365
- end
1366
- </ruby>
1367
-
1368
- h6(#has_many-include). +:include+
1369
-
1370
- 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:
1371
-
1372
- <ruby>
1373
- class Customer < ActiveRecord::Base
1374
- has_many :orders
1375
- end
1376
-
1377
- class Order < ActiveRecord::Base
1378
- belongs_to :customer
1379
- has_many :line_items
1380
- end
1381
-
1382
- class LineItem < ActiveRecord::Base
1383
- belongs_to :order
1384
- end
1385
- </ruby>
1386
-
1387
- 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:
1388
-
1389
- <ruby>
1390
- class Customer < ActiveRecord::Base
1391
- has_many :orders, :include => :line_items
1392
- end
1393
-
1394
- class Order < ActiveRecord::Base
1395
- belongs_to :customer
1396
- has_many :line_items
1397
- end
1398
-
1399
- class LineItem < ActiveRecord::Base
1400
- belongs_to :order
1401
- end
1402
- </ruby>
1403
-
1404
- h6(#has_many-inverse_of). +:inverse_of+
1405
-
1406
- The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options.
1407
-
1408
- <ruby>
1409
- class Customer < ActiveRecord::Base
1410
- has_many :orders, :inverse_of => :customer
1411
- end
1412
-
1413
- class Order < ActiveRecord::Base
1414
- belongs_to :customer, :inverse_of => :orders
1415
- end
1416
- </ruby>
1417
-
1418
- h6(#has_many-limit). +:limit+
1419
-
1420
- The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
1421
-
1422
- <ruby>
1423
- class Customer < ActiveRecord::Base
1424
- has_many :recent_orders, :class_name => "Order",
1425
- :order => "order_date DESC", :limit => 100
1426
- end
1427
- </ruby>
1428
-
1429
- h6(#has_many-offset). +:offset+
1430
-
1431
- 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.
1432
-
1433
- h6(#has_many-order). +:order+
1434
-
1435
- The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause).
1436
-
1437
- <ruby>
1438
- class Customer < ActiveRecord::Base
1439
- has_many :orders, :order => "date_confirmed DESC"
1440
- end
1441
- </ruby>
1442
-
1443
- h6(#has_many-primary_key). +:primary_key+
1444
-
1445
- By convention, Rails assumes 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.
1446
-
1447
- h6(#has_many-readonly). +:readonly+
1448
-
1449
- If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
1450
-
1451
- h6(#has_many-select). +:select+
1452
-
1453
- 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.
1454
-
1455
- 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.
1456
-
1457
- h6(#has_many-source). +:source+
1458
-
1459
- 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.
1460
-
1461
- h6(#has_many-source_type). +:source_type+
1462
-
1463
- The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
1464
-
1465
- h6(#has_many-through). +:through+
1466
-
1467
- 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>.
1468
-
1469
- h6(#has_many-uniq). +:uniq+
1470
-
1471
- Set the +:uniq+ option to true to keep the collection free of duplicates. This is mostly useful together with the +:through+ option.
1472
-
1473
- <ruby>
1474
- class Person < ActiveRecord::Base
1475
- has_many :readings
1476
- has_many :posts, :through => :readings
1477
- end
1478
-
1479
- person = Person.create(:name => 'john')
1480
- post = Post.create(:name => 'a1')
1481
- person.posts << post
1482
- person.posts << post
1483
- person.posts.inspect # => [#<Post id: 5, name: "a1">, #<Post id: 5, name: "a1">]
1484
- Reading.all.inspect # => [#<Reading id: 12, person_id: 5, post_id: 5>, #<Reading id: 13, person_id: 5, post_id: 5>]
1485
- </ruby>
1486
-
1487
- In the above case there are two readings and +person.posts+ brings out both of them even though these records are pointing to the same post.
1488
-
1489
- Now let's set +:uniq+ to true:
1490
-
1491
- <ruby>
1492
- class Person
1493
- has_many :readings
1494
- has_many :posts, :through => :readings, :uniq => true
1495
- end
1496
-
1497
- person = Person.create(:name => 'honda')
1498
- post = Post.create(:name => 'a1')
1499
- person.posts << post
1500
- person.posts << post
1501
- person.posts.inspect # => [#<Post id: 7, name: "a1">]
1502
- Reading.all.inspect # => [#<Reading id: 16, person_id: 7, post_id: 7>, #<Reading id: 17, person_id: 7, post_id: 7>]
1503
- </ruby>
1504
-
1505
- In the above case there are still two readings. However +person.posts+ shows only one post because the collection loads only unique records.
1506
-
1507
- h6(#has_many-validate). +:validate+
1508
-
1509
- 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.
1510
-
1511
- h5(#has_many-when_are_objects_saved). When are Objects Saved?
1512
-
1513
- 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.
1514
-
1515
- If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1516
-
1517
- 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.
1518
-
1519
- 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.
1520
-
1521
- h4. +has_and_belongs_to_many+ Association Reference
1522
-
1523
- 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.
1524
-
1525
- h5. Methods Added by +has_and_belongs_to_many+
1526
-
1527
- When you declare a +has_and_belongs_to_many+ association, the declaring class automatically gains 13 methods related to the association:
1528
-
1529
- * <tt><em>collection</em>(force_reload = false)</tt>
1530
- * <tt><em>collection</em><<(object, ...)</tt>
1531
- * <tt><em>collection</em>.delete(object, ...)</tt>
1532
- * <tt><em>collection</em>=objects</tt>
1533
- * <tt><em>collection_singular</em>_ids</tt>
1534
- * <tt><em>collection_singular</em>_ids=ids</tt>
1535
- * <tt><em>collection</em>.clear</tt>
1536
- * <tt><em>collection</em>.empty?</tt>
1537
- * <tt><em>collection</em>.size</tt>
1538
- * <tt><em>collection</em>.find(...)</tt>
1539
- * <tt><em>collection</em>.where(...)</tt>
1540
- * <tt><em>collection</em>.exists?(...)</tt>
1541
- * <tt><em>collection</em>.build(attributes = {})</tt>
1542
- * <tt><em>collection</em>.create(attributes = {})</tt>
1543
-
1544
- 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:
1545
-
1546
- <ruby>
1547
- class Part < ActiveRecord::Base
1548
- has_and_belongs_to_many :assemblies
1549
- end
1550
- </ruby>
1551
-
1552
- Each instance of the part model will have these methods:
1553
-
1554
- <ruby>
1555
- assemblies(force_reload = false)
1556
- assemblies<<(object, ...)
1557
- assemblies.delete(object, ...)
1558
- assemblies=objects
1559
- assembly_ids
1560
- assembly_ids=ids
1561
- assemblies.clear
1562
- assemblies.empty?
1563
- assemblies.size
1564
- assemblies.find(...)
1565
- assemblies.where(...)
1566
- assemblies.exists?(...)
1567
- assemblies.build(attributes = {}, ...)
1568
- assemblies.create(attributes = {})
1569
- </ruby>
1570
-
1571
- h6. Additional Column Methods
1572
-
1573
- 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.
1574
-
1575
- 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+.
1576
-
1577
-
1578
- h6(#has_and_belongs_to_many-collection). <tt><em>collection</em>(force_reload = false)</tt>
1579
-
1580
- 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.
1581
-
1582
- <ruby>
1583
- @assemblies = @part.assemblies
1584
- </ruby>
1585
-
1586
- h6(#has_and_belongs_to_many-collection-lt_lt). <tt><em>collection</em><<(object, ...)</tt>
1587
-
1588
- The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by creating records in the join table.
1589
-
1590
- <ruby>
1591
- @part.assemblies << @assembly1
1592
- </ruby>
1593
-
1594
- NOTE: This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>.
1595
-
1596
- h6(#has_and_belongs_to_many-collection-delete). <tt><em>collection</em>.delete(object, ...)</tt>
1597
-
1598
- 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.
1599
-
1600
- <ruby>
1601
- @part.assemblies.delete(@assembly1)
1602
- </ruby>
1603
-
1604
- h6(#has_and_belongs_to_many-collection-equal). <tt><em>collection</em>=objects</tt>
1605
-
1606
- The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
1607
-
1608
- h6(#has_and_belongs_to_many-collection_singular). <tt><em>collection_singular</em>_ids</tt>
1609
-
1610
- The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.
1611
-
1612
- <ruby>
1613
- @assembly_ids = @part.assembly_ids
1614
- </ruby>
1615
-
1616
- h6(#has_and_belongs_to_many-collection_singular_ids_ids). <tt><em>collection_singular</em>_ids=ids</tt>
1617
-
1618
- 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.
1619
-
1620
- h6(#has_and_belongs_to_many-collection-clear). <tt><em>collection</em>.clear</tt>
1621
-
1622
- 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.
1623
-
1624
- h6(#has_and_belongs_to_many-collection-empty). <tt><em>collection</em>.empty?</tt>
1625
-
1626
- The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.
1627
-
1628
- <ruby>
1629
- <% if @part.assemblies.empty? %>
1630
- This part is not used in any assemblies
1631
- <% end %>
1632
- </ruby>
1633
-
1634
- h6(#has_and_belongs_to_many-collection-size). <tt><em>collection</em>.size</tt>
1635
-
1636
- The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.
1637
-
1638
- <ruby>
1639
- @assembly_count = @part.assemblies.size
1640
- </ruby>
1641
-
1642
- h6(#has_and_belongs_to_many-collection-find). <tt><em>collection</em>.find(...)</tt>
1643
-
1644
- 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.
1645
-
1646
- <ruby>
1647
- @new_assemblies = @part.assemblies.all(
1648
- :conditions => ["created_at > ?", 2.days.ago])
1649
- </ruby>
1650
-
1651
- NOTE: Beginning with Rails 3, supplying options to the +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions.
1652
-
1653
- h6(#has_and_belongs_to_many-collection-where). <tt><em>collection</em>.where(...)</tt>
1654
-
1655
- The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection.
1656
-
1657
- <ruby>
1658
- @new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago)
1659
- </ruby>
1660
-
1661
- h6(#has_and_belongs_to_many-collection-exists). <tt><em>collection</em>.exists?(...)</tt>
1662
-
1663
- 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?+.
1664
-
1665
- h6(#has_and_belongs_to_many-collection-build). <tt><em>collection</em>.build(attributes = {})</tt>
1666
-
1667
- 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.
1668
-
1669
- <ruby>
1670
- @assembly = @part.assemblies.build(
1671
- {:assembly_name => "Transmission housing"})
1672
- </ruby>
1673
-
1674
- h6(#has_and_belongs_to_many-create-attributes). <tt><em>collection</em>.create(attributes = {})</tt>
1675
-
1676
- 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, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
1677
-
1678
- <ruby>
1679
- @assembly = @part.assemblies.create(
1680
- {:assembly_name => "Transmission housing"})
1681
- </ruby>
1682
-
1683
- h5. Options for +has_and_belongs_to_many+
1684
-
1685
- While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +has_and_belongs_to_many+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
1686
-
1687
- <ruby>
1688
- class Parts < ActiveRecord::Base
1689
- has_and_belongs_to_many :assemblies, :uniq => true,
1690
- :read_only => true
1691
- end
1692
- </ruby>
1693
-
1694
- The +has_and_belongs_to_many+ association supports these options:
1695
-
1696
- * +:association_foreign_key+
1697
- * +:autosave+
1698
- * +:class_name+
1699
- * +:conditions+
1700
- * +:counter_sql+
1701
- * +:delete_sql+
1702
- * +:extend+
1703
- * +:finder_sql+
1704
- * +:foreign_key+
1705
- * +:group+
1706
- * +:include+
1707
- * +:insert_sql+
1708
- * +:join_table+
1709
- * +:limit+
1710
- * +:offset+
1711
- * +:order+
1712
- * +:readonly+
1713
- * +:select+
1714
- * +:uniq+
1715
- * +:validate+
1716
-
1717
- h6(#has_and_belongs_to_many-association_foreign_key). +:association_foreign_key+
1718
-
1719
- By convention, Rails assumes 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:
1720
-
1721
- TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when setting up a many-to-many self-join. For example:
1722
-
1723
- <ruby>
1724
- class User < ActiveRecord::Base
1725
- has_and_belongs_to_many :friends, :class_name => "User",
1726
- :foreign_key => "this_user_id",
1727
- :association_foreign_key => "other_user_id"
1728
- end
1729
- </ruby>
1730
-
1731
- h6(#has_and_belongs_to_many-autosave). +:autosave+
1732
-
1733
- 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.
1734
-
1735
- h6(#has_and_belongs_to_many-class_name). +:class_name+
1736
-
1737
- 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:
1738
-
1739
- <ruby>
1740
- class Parts < ActiveRecord::Base
1741
- has_and_belongs_to_many :assemblies, :class_name => "Gadget"
1742
- end
1743
- </ruby>
1744
-
1745
- h6(#has_and_belongs_to_many-conditions). +:conditions+
1746
-
1747
- The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
1748
-
1749
- <ruby>
1750
- class Parts < ActiveRecord::Base
1751
- has_and_belongs_to_many :assemblies,
1752
- :conditions => "factory = 'Seattle'"
1753
- end
1754
- </ruby>
1755
-
1756
- You can also set conditions via a hash:
1757
-
1758
- <ruby>
1759
- class Parts < ActiveRecord::Base
1760
- has_and_belongs_to_many :assemblies,
1761
- :conditions => { :factory => 'Seattle' }
1762
- end
1763
- </ruby>
1764
-
1765
- 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".
1766
-
1767
- h6(#has_and_belongs_to_many-counter_sql). +:counter_sql+
1768
-
1769
- 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.
1770
-
1771
- 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.
1772
-
1773
- h6(#has_and_belongs_to_many-delete_sql). +:delete_sql+
1774
-
1775
- 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.
1776
-
1777
- h6(#has_and_belongs_to_many-extend). +:extend+
1778
-
1779
- 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>.
1780
-
1781
- h6(#has_and_belongs_to_many-finder_sql). +:finder_sql+
1782
-
1783
- 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.
1784
-
1785
- h6(#has_and_belongs_to_many-foreign_key). +:foreign_key+
1786
-
1787
- By convention, Rails assumes 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:
1788
-
1789
- <ruby>
1790
- class User < ActiveRecord::Base
1791
- has_and_belongs_to_many :friends, :class_name => "User",
1792
- :foreign_key => "this_user_id",
1793
- :association_foreign_key => "other_user_id"
1794
- end
1795
- </ruby>
1796
-
1797
- h6(#has_and_belongs_to_many-group). +:group+
1798
-
1799
- The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
1800
-
1801
- <ruby>
1802
- class Parts < ActiveRecord::Base
1803
- has_and_belongs_to_many :assemblies, :group => "factory"
1804
- end
1805
- </ruby>
1806
-
1807
- h6(#has_and_belongs_to_many-include). +:include+
1808
-
1809
- You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used.
1810
-
1811
- h6(#has_and_belongs_to_many-insert_sql). +:insert_sql+
1812
-
1813
- 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.
1814
-
1815
- h6(#has_and_belongs_to_many-join_table). +:join_table+
1816
-
1817
- 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.
1818
-
1819
- h6(#has_and_belongs_to_many-limit). +:limit+
1820
-
1821
- The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
1822
-
1823
- <ruby>
1824
- class Parts < ActiveRecord::Base
1825
- has_and_belongs_to_many :assemblies, :order => "created_at DESC",
1826
- :limit => 50
1827
- end
1828
- </ruby>
1829
-
1830
- h6(#has_and_belongs_to_many-offset). +:offset+
1831
-
1832
- 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.
1833
-
1834
- h6(#has_and_belongs_to_many-order). +:order+
1835
-
1836
- The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause).
1837
-
1838
- <ruby>
1839
- class Parts < ActiveRecord::Base
1840
- has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
1841
- end
1842
- </ruby>
1843
-
1844
- h6(#has_and_belongs_to_many-readonly). +:readonly+
1845
-
1846
- If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
1847
-
1848
- h6(#has_and_belongs_to_many-select). +:select+
1849
-
1850
- 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.
1851
-
1852
- h6(#has_and_belongs_to_many-uniq). +:uniq+
1853
-
1854
- Specify the +:uniq => true+ option to remove duplicates from the collection.
1855
-
1856
- h6(#has_and_belongs_to_many-validate). +:validate+
1857
-
1858
- 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.
1859
-
1860
- h5(#has_and_belongs_to_many-when_are_objects_saved). When are Objects Saved?
1861
-
1862
- 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.
1863
-
1864
- If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1865
-
1866
- 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.
1867
-
1868
- 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.
1869
-
1870
- h4. Association Callbacks
1871
-
1872
- Normal callbacks hook into the life cycle 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.
1873
-
1874
- Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection. There are four available association callbacks:
1875
-
1876
- * +before_add+
1877
- * +after_add+
1878
- * +before_remove+
1879
- * +after_remove+
1880
-
1881
- You define association callbacks by adding options to the association declaration. For example:
1882
-
1883
- <ruby>
1884
- class Customer < ActiveRecord::Base
1885
- has_many :orders, :before_add => :check_credit_limit
1886
-
1887
- def check_credit_limit(order)
1888
- ...
1889
- end
1890
- end
1891
- </ruby>
1892
-
1893
- Rails passes the object being added or removed to the callback.
1894
-
1895
- You can stack callbacks on a single event by passing them as an array:
1896
-
1897
- <ruby>
1898
- class Customer < ActiveRecord::Base
1899
- has_many :orders,
1900
- :before_add => [:check_credit_limit, :calculate_shipping_charges]
1901
-
1902
- def check_credit_limit(order)
1903
- ...
1904
- end
1905
-
1906
- def calculate_shipping_charges(order)
1907
- ...
1908
- end
1909
- end
1910
- </ruby>
1911
-
1912
- 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.
1913
-
1914
- h4. Association Extensions
1915
-
1916
- 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:
1917
-
1918
- <ruby>
1919
- class Customer < ActiveRecord::Base
1920
- has_many :orders do
1921
- def find_by_order_prefix(order_number)
1922
- find_by_region_id(order_number[0..2])
1923
- end
1924
- end
1925
- end
1926
- </ruby>
1927
-
1928
- If you have an extension that should be shared by many associations, you can use a named extension module. For example:
1929
-
1930
- <ruby>
1931
- module FindRecentExtension
1932
- def find_recent
1933
- where("created_at > ?", 5.days.ago)
1934
- end
1935
- end
1936
-
1937
- class Customer < ActiveRecord::Base
1938
- has_many :orders, :extend => FindRecentExtension
1939
- end
1940
-
1941
- class Supplier < ActiveRecord::Base
1942
- has_many :deliveries, :extend => FindRecentExtension
1943
- end
1944
- </ruby>
1945
-
1946
- To include more than one extension module in a single association, specify an array of modules:
1947
-
1948
- <ruby>
1949
- class Customer < ActiveRecord::Base
1950
- has_many :orders,
1951
- :extend => [FindRecentExtension, FindActiveExtension]
1952
- end
1953
- </ruby>
1954
-
1955
- Extensions can refer to the internals of the association proxy using these three attributes of the +proxy_association+ accessor:
1956
-
1957
- * +proxy_association.owner+ returns the object that the association is a part of.
1958
- * +proxy_association.reflection+ returns the reflection object that describes the association.
1959
- * +proxy_association.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+.