rails 2.2.2 → 3.0.0

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

Potentially problematic release.


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

Files changed (336) hide show
  1. data/bin/rails +8 -18
  2. metadata +118 -452
  3. data/CHANGELOG +0 -2071
  4. data/MIT-LICENSE +0 -20
  5. data/README +0 -256
  6. data/Rakefile +0 -411
  7. data/bin/about +0 -4
  8. data/bin/console +0 -3
  9. data/bin/dbconsole +0 -3
  10. data/bin/destroy +0 -3
  11. data/bin/generate +0 -3
  12. data/bin/performance/benchmarker +0 -3
  13. data/bin/performance/profiler +0 -3
  14. data/bin/performance/request +0 -3
  15. data/bin/plugin +0 -3
  16. data/bin/process/inspector +0 -3
  17. data/bin/process/reaper +0 -3
  18. data/bin/process/spawner +0 -3
  19. data/bin/runner +0 -3
  20. data/bin/server +0 -3
  21. data/builtin/rails_info/rails/info.rb +0 -125
  22. data/builtin/rails_info/rails/info_controller.rb +0 -9
  23. data/builtin/rails_info/rails/info_helper.rb +0 -2
  24. data/builtin/rails_info/rails_info_controller.rb +0 -2
  25. data/config.ru +0 -17
  26. data/configs/apache.conf +0 -40
  27. data/configs/databases/frontbase.yml +0 -28
  28. data/configs/databases/ibm_db.yml +0 -62
  29. data/configs/databases/mysql.yml +0 -57
  30. data/configs/databases/oracle.yml +0 -39
  31. data/configs/databases/postgresql.yml +0 -51
  32. data/configs/databases/sqlite2.yml +0 -19
  33. data/configs/databases/sqlite3.yml +0 -22
  34. data/configs/empty.log +0 -0
  35. data/configs/initializers/inflections.rb +0 -10
  36. data/configs/initializers/mime_types.rb +0 -5
  37. data/configs/initializers/new_rails_defaults.rb +0 -17
  38. data/configs/lighttpd.conf +0 -54
  39. data/configs/locales/en.yml +0 -5
  40. data/configs/routes.rb +0 -43
  41. data/dispatches/dispatch.fcgi +0 -24
  42. data/dispatches/dispatch.rb +0 -10
  43. data/dispatches/gateway.cgi +0 -97
  44. data/doc/README_FOR_APP +0 -5
  45. data/doc/guides/html/2_2_release_notes.html +0 -1185
  46. data/doc/guides/html/actioncontroller_basics.html +0 -1270
  47. data/doc/guides/html/activerecord_validations_callbacks.html +0 -749
  48. data/doc/guides/html/association_basics.html +0 -2585
  49. data/doc/guides/html/authors.html +0 -240
  50. data/doc/guides/html/benchmarking_and_profiling.html +0 -1018
  51. data/doc/guides/html/caching_with_rails.html +0 -583
  52. data/doc/guides/html/command_line.html +0 -434
  53. data/doc/guides/html/configuring.html +0 -438
  54. data/doc/guides/html/creating_plugins.html +0 -1594
  55. data/doc/guides/html/debugging_rails_applications.html +0 -1175
  56. data/doc/guides/html/finders.html +0 -1090
  57. data/doc/guides/html/form_helpers.html +0 -638
  58. data/doc/guides/html/getting_started_with_rails.html +0 -2066
  59. data/doc/guides/html/index.html +0 -349
  60. data/doc/guides/html/layouts_and_rendering.html +0 -1406
  61. data/doc/guides/html/migrations.html +0 -921
  62. data/doc/guides/html/routing_outside_in.html +0 -2213
  63. data/doc/guides/html/security.html +0 -1346
  64. data/doc/guides/html/testing_rails_applications.html +0 -1859
  65. data/doc/guides/source/2_2_release_notes.txt +0 -435
  66. data/doc/guides/source/actioncontroller_basics/changelog.txt +0 -5
  67. data/doc/guides/source/actioncontroller_basics/cookies.txt +0 -34
  68. data/doc/guides/source/actioncontroller_basics/csrf.txt +0 -32
  69. data/doc/guides/source/actioncontroller_basics/filters.txt +0 -119
  70. data/doc/guides/source/actioncontroller_basics/http_auth.txt +0 -24
  71. data/doc/guides/source/actioncontroller_basics/index.txt +0 -40
  72. data/doc/guides/source/actioncontroller_basics/introduction.txt +0 -9
  73. data/doc/guides/source/actioncontroller_basics/methods.txt +0 -39
  74. data/doc/guides/source/actioncontroller_basics/parameter_filtering.txt +0 -14
  75. data/doc/guides/source/actioncontroller_basics/params.txt +0 -93
  76. data/doc/guides/source/actioncontroller_basics/request_response_objects.txt +0 -43
  77. data/doc/guides/source/actioncontroller_basics/rescue.txt +0 -67
  78. data/doc/guides/source/actioncontroller_basics/session.txt +0 -187
  79. data/doc/guides/source/actioncontroller_basics/streaming.txt +0 -91
  80. data/doc/guides/source/actioncontroller_basics/verification.txt +0 -40
  81. data/doc/guides/source/active_record_basics.txt +0 -181
  82. data/doc/guides/source/activerecord_validations_callbacks.txt +0 -404
  83. data/doc/guides/source/association_basics.txt +0 -1840
  84. data/doc/guides/source/authors.txt +0 -39
  85. data/doc/guides/source/benchmarking_and_profiling/appendix.txt +0 -95
  86. data/doc/guides/source/benchmarking_and_profiling/digging_deeper.txt +0 -105
  87. data/doc/guides/source/benchmarking_and_profiling/edge_rails_features.txt +0 -185
  88. data/doc/guides/source/benchmarking_and_profiling/gameplan.txt +0 -27
  89. data/doc/guides/source/benchmarking_and_profiling/index.txt +0 -242
  90. data/doc/guides/source/benchmarking_and_profiling/rubyprof.txt +0 -179
  91. data/doc/guides/source/benchmarking_and_profiling/statistics.txt +0 -57
  92. data/doc/guides/source/caching_with_rails.txt +0 -367
  93. data/doc/guides/source/command_line.txt +0 -147
  94. data/doc/guides/source/configuring.txt +0 -225
  95. data/doc/guides/source/creating_plugins/acts_as_yaffle.txt +0 -191
  96. data/doc/guides/source/creating_plugins/appendix.txt +0 -46
  97. data/doc/guides/source/creating_plugins/controllers.txt +0 -59
  98. data/doc/guides/source/creating_plugins/core_ext.txt +0 -123
  99. data/doc/guides/source/creating_plugins/custom_route.txt +0 -69
  100. data/doc/guides/source/creating_plugins/gem.txt +0 -1
  101. data/doc/guides/source/creating_plugins/generator_method.txt +0 -89
  102. data/doc/guides/source/creating_plugins/helpers.txt +0 -51
  103. data/doc/guides/source/creating_plugins/index.txt +0 -52
  104. data/doc/guides/source/creating_plugins/migration_generator.txt +0 -156
  105. data/doc/guides/source/creating_plugins/models.txt +0 -76
  106. data/doc/guides/source/creating_plugins/odds_and_ends.txt +0 -69
  107. data/doc/guides/source/creating_plugins/test_setup.txt +0 -230
  108. data/doc/guides/source/debugging_rails_applications.txt +0 -733
  109. data/doc/guides/source/finders.txt +0 -668
  110. data/doc/guides/source/form_helpers.txt +0 -345
  111. data/doc/guides/source/getting_started_with_rails.txt +0 -1256
  112. data/doc/guides/source/images/belongs_to.png +0 -0
  113. data/doc/guides/source/images/bullet.gif +0 -0
  114. data/doc/guides/source/images/csrf.png +0 -0
  115. data/doc/guides/source/images/habtm.png +0 -0
  116. data/doc/guides/source/images/has_many.png +0 -0
  117. data/doc/guides/source/images/has_many_through.png +0 -0
  118. data/doc/guides/source/images/has_one.png +0 -0
  119. data/doc/guides/source/images/has_one_through.png +0 -0
  120. data/doc/guides/source/images/header_backdrop.png +0 -0
  121. data/doc/guides/source/images/icons/README +0 -5
  122. data/doc/guides/source/images/icons/callouts/1.png +0 -0
  123. data/doc/guides/source/images/icons/callouts/10.png +0 -0
  124. data/doc/guides/source/images/icons/callouts/11.png +0 -0
  125. data/doc/guides/source/images/icons/callouts/12.png +0 -0
  126. data/doc/guides/source/images/icons/callouts/13.png +0 -0
  127. data/doc/guides/source/images/icons/callouts/14.png +0 -0
  128. data/doc/guides/source/images/icons/callouts/15.png +0 -0
  129. data/doc/guides/source/images/icons/callouts/2.png +0 -0
  130. data/doc/guides/source/images/icons/callouts/3.png +0 -0
  131. data/doc/guides/source/images/icons/callouts/4.png +0 -0
  132. data/doc/guides/source/images/icons/callouts/5.png +0 -0
  133. data/doc/guides/source/images/icons/callouts/6.png +0 -0
  134. data/doc/guides/source/images/icons/callouts/7.png +0 -0
  135. data/doc/guides/source/images/icons/callouts/8.png +0 -0
  136. data/doc/guides/source/images/icons/callouts/9.png +0 -0
  137. data/doc/guides/source/images/icons/caution.png +0 -0
  138. data/doc/guides/source/images/icons/example.png +0 -0
  139. data/doc/guides/source/images/icons/home.png +0 -0
  140. data/doc/guides/source/images/icons/important.png +0 -0
  141. data/doc/guides/source/images/icons/next.png +0 -0
  142. data/doc/guides/source/images/icons/note.png +0 -0
  143. data/doc/guides/source/images/icons/prev.png +0 -0
  144. data/doc/guides/source/images/icons/tip.png +0 -0
  145. data/doc/guides/source/images/icons/up.png +0 -0
  146. data/doc/guides/source/images/icons/warning.png +0 -0
  147. data/doc/guides/source/images/polymorphic.png +0 -0
  148. data/doc/guides/source/images/rails_logo_remix.gif +0 -0
  149. data/doc/guides/source/images/ruby_on_rails_by_mike_rundle2.gif +0 -0
  150. data/doc/guides/source/images/session_fixation.png +0 -0
  151. data/doc/guides/source/index.txt +0 -118
  152. data/doc/guides/source/layouts_and_rendering.txt +0 -982
  153. data/doc/guides/source/migrations/anatomy_of_a_migration.txt +0 -85
  154. data/doc/guides/source/migrations/changelog.txt +0 -5
  155. data/doc/guides/source/migrations/creating_a_migration.txt +0 -109
  156. data/doc/guides/source/migrations/foreign_keys.txt +0 -8
  157. data/doc/guides/source/migrations/index.txt +0 -22
  158. data/doc/guides/source/migrations/rakeing_around.txt +0 -111
  159. data/doc/guides/source/migrations/scheming.txt +0 -47
  160. data/doc/guides/source/migrations/using_models_in_migrations.txt +0 -46
  161. data/doc/guides/source/migrations/writing_a_migration.txt +0 -159
  162. data/doc/guides/source/routing_outside_in.txt +0 -986
  163. data/doc/guides/source/security.txt +0 -984
  164. data/doc/guides/source/stylesheets/base.css +0 -358
  165. data/doc/guides/source/stylesheets/forms.css +0 -35
  166. data/doc/guides/source/stylesheets/more.css +0 -82
  167. data/doc/guides/source/templates/guides.html.erb +0 -97
  168. data/doc/guides/source/templates/inline.css +0 -165
  169. data/doc/guides/source/testing_rails_applications.txt +0 -995
  170. data/environments/boot.rb +0 -109
  171. data/environments/development.rb +0 -17
  172. data/environments/environment.rb +0 -75
  173. data/environments/production.rb +0 -24
  174. data/environments/test.rb +0 -22
  175. data/fresh_rakefile +0 -10
  176. data/helpers/application.rb +0 -15
  177. data/helpers/application_helper.rb +0 -3
  178. data/helpers/performance_test.rb +0 -9
  179. data/helpers/test_helper.rb +0 -38
  180. data/html/404.html +0 -30
  181. data/html/422.html +0 -30
  182. data/html/500.html +0 -33
  183. data/html/favicon.ico +0 -0
  184. data/html/images/rails.png +0 -0
  185. data/html/index.html +0 -274
  186. data/html/javascripts/application.js +0 -2
  187. data/html/javascripts/controls.js +0 -963
  188. data/html/javascripts/dragdrop.js +0 -973
  189. data/html/javascripts/effects.js +0 -1128
  190. data/html/javascripts/prototype.js +0 -4320
  191. data/html/robots.txt +0 -5
  192. data/lib/code_statistics.rb +0 -107
  193. data/lib/commands.rb +0 -17
  194. data/lib/commands/about.rb +0 -3
  195. data/lib/commands/console.rb +0 -45
  196. data/lib/commands/dbconsole.rb +0 -67
  197. data/lib/commands/destroy.rb +0 -6
  198. data/lib/commands/generate.rb +0 -6
  199. data/lib/commands/ncgi/listener +0 -86
  200. data/lib/commands/ncgi/tracker +0 -69
  201. data/lib/commands/performance/benchmarker.rb +0 -24
  202. data/lib/commands/performance/profiler.rb +0 -50
  203. data/lib/commands/performance/request.rb +0 -6
  204. data/lib/commands/plugin.rb +0 -967
  205. data/lib/commands/process/inspector.rb +0 -68
  206. data/lib/commands/process/reaper.rb +0 -149
  207. data/lib/commands/process/spawner.rb +0 -219
  208. data/lib/commands/process/spinner.rb +0 -57
  209. data/lib/commands/runner.rb +0 -48
  210. data/lib/commands/server.rb +0 -49
  211. data/lib/commands/servers/base.rb +0 -31
  212. data/lib/commands/servers/lighttpd.rb +0 -94
  213. data/lib/commands/servers/mongrel.rb +0 -69
  214. data/lib/commands/servers/new_mongrel.rb +0 -16
  215. data/lib/commands/servers/thin.rb +0 -25
  216. data/lib/commands/servers/webrick.rb +0 -66
  217. data/lib/commands/update.rb +0 -4
  218. data/lib/console_app.rb +0 -30
  219. data/lib/console_sandbox.rb +0 -6
  220. data/lib/console_with_helpers.rb +0 -26
  221. data/lib/dispatcher.rb +0 -24
  222. data/lib/fcgi_handler.rb +0 -237
  223. data/lib/initializer.rb +0 -1038
  224. data/lib/performance_test_help.rb +0 -5
  225. data/lib/rails/gem_builder.rb +0 -21
  226. data/lib/rails/gem_dependency.rb +0 -251
  227. data/lib/rails/mongrel_server/commands.rb +0 -342
  228. data/lib/rails/mongrel_server/handler.rb +0 -55
  229. data/lib/rails/plugin.rb +0 -124
  230. data/lib/rails/plugin/loader.rb +0 -152
  231. data/lib/rails/plugin/locator.rb +0 -100
  232. data/lib/rails/rack.rb +0 -6
  233. data/lib/rails/rack/logger.rb +0 -28
  234. data/lib/rails/rack/static.rb +0 -35
  235. data/lib/rails/vendor_gem_source_index.rb +0 -140
  236. data/lib/rails/version.rb +0 -9
  237. data/lib/rails_generator.rb +0 -43
  238. data/lib/rails_generator/base.rb +0 -263
  239. data/lib/rails_generator/commands.rb +0 -616
  240. data/lib/rails_generator/generated_attribute.rb +0 -46
  241. data/lib/rails_generator/generators/applications/app/USAGE +0 -9
  242. data/lib/rails_generator/generators/applications/app/app_generator.rb +0 -184
  243. data/lib/rails_generator/generators/components/controller/USAGE +0 -29
  244. data/lib/rails_generator/generators/components/controller/controller_generator.rb +0 -37
  245. data/lib/rails_generator/generators/components/controller/templates/controller.rb +0 -7
  246. data/lib/rails_generator/generators/components/controller/templates/functional_test.rb +0 -8
  247. data/lib/rails_generator/generators/components/controller/templates/helper.rb +0 -2
  248. data/lib/rails_generator/generators/components/controller/templates/view.html.erb +0 -2
  249. data/lib/rails_generator/generators/components/integration_test/USAGE +0 -8
  250. data/lib/rails_generator/generators/components/integration_test/integration_test_generator.rb +0 -16
  251. data/lib/rails_generator/generators/components/integration_test/templates/integration_test.rb +0 -10
  252. data/lib/rails_generator/generators/components/mailer/USAGE +0 -16
  253. data/lib/rails_generator/generators/components/mailer/mailer_generator.rb +0 -30
  254. data/lib/rails_generator/generators/components/mailer/templates/fixture.erb +0 -3
  255. data/lib/rails_generator/generators/components/mailer/templates/fixture.rhtml +0 -0
  256. data/lib/rails_generator/generators/components/mailer/templates/mailer.rb +0 -15
  257. data/lib/rails_generator/generators/components/mailer/templates/unit_test.rb +0 -20
  258. data/lib/rails_generator/generators/components/mailer/templates/view.erb +0 -3
  259. data/lib/rails_generator/generators/components/mailer/templates/view.rhtml +0 -0
  260. data/lib/rails_generator/generators/components/migration/USAGE +0 -29
  261. data/lib/rails_generator/generators/components/migration/migration_generator.rb +0 -20
  262. data/lib/rails_generator/generators/components/migration/templates/migration.rb +0 -11
  263. data/lib/rails_generator/generators/components/model/USAGE +0 -27
  264. data/lib/rails_generator/generators/components/model/model_generator.rb +0 -45
  265. data/lib/rails_generator/generators/components/model/templates/fixtures.yml +0 -19
  266. data/lib/rails_generator/generators/components/model/templates/migration.rb +0 -16
  267. data/lib/rails_generator/generators/components/model/templates/model.rb +0 -5
  268. data/lib/rails_generator/generators/components/model/templates/unit_test.rb +0 -8
  269. data/lib/rails_generator/generators/components/observer/USAGE +0 -13
  270. data/lib/rails_generator/generators/components/observer/observer_generator.rb +0 -16
  271. data/lib/rails_generator/generators/components/observer/templates/observer.rb +0 -2
  272. data/lib/rails_generator/generators/components/observer/templates/unit_test.rb +0 -8
  273. data/lib/rails_generator/generators/components/performance_test/USAGE +0 -8
  274. data/lib/rails_generator/generators/components/performance_test/performance_test_generator.rb +0 -16
  275. data/lib/rails_generator/generators/components/performance_test/templates/performance_test.rb +0 -9
  276. data/lib/rails_generator/generators/components/plugin/USAGE +0 -25
  277. data/lib/rails_generator/generators/components/plugin/plugin_generator.rb +0 -39
  278. data/lib/rails_generator/generators/components/plugin/templates/MIT-LICENSE +0 -20
  279. data/lib/rails_generator/generators/components/plugin/templates/README +0 -13
  280. data/lib/rails_generator/generators/components/plugin/templates/Rakefile +0 -23
  281. data/lib/rails_generator/generators/components/plugin/templates/USAGE +0 -8
  282. data/lib/rails_generator/generators/components/plugin/templates/generator.rb +0 -8
  283. data/lib/rails_generator/generators/components/plugin/templates/init.rb +0 -1
  284. data/lib/rails_generator/generators/components/plugin/templates/install.rb +0 -1
  285. data/lib/rails_generator/generators/components/plugin/templates/plugin.rb +0 -1
  286. data/lib/rails_generator/generators/components/plugin/templates/tasks.rake +0 -4
  287. data/lib/rails_generator/generators/components/plugin/templates/test_helper.rb +0 -3
  288. data/lib/rails_generator/generators/components/plugin/templates/uninstall.rb +0 -1
  289. data/lib/rails_generator/generators/components/plugin/templates/unit_test.rb +0 -8
  290. data/lib/rails_generator/generators/components/resource/USAGE +0 -23
  291. data/lib/rails_generator/generators/components/resource/resource_generator.rb +0 -74
  292. data/lib/rails_generator/generators/components/resource/templates/controller.rb +0 -2
  293. data/lib/rails_generator/generators/components/resource/templates/functional_test.rb +0 -8
  294. data/lib/rails_generator/generators/components/resource/templates/helper.rb +0 -2
  295. data/lib/rails_generator/generators/components/scaffold/USAGE +0 -29
  296. data/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb +0 -100
  297. data/lib/rails_generator/generators/components/scaffold/templates/controller.rb +0 -85
  298. data/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb +0 -45
  299. data/lib/rails_generator/generators/components/scaffold/templates/helper.rb +0 -2
  300. data/lib/rails_generator/generators/components/scaffold/templates/layout.html.erb +0 -17
  301. data/lib/rails_generator/generators/components/scaffold/templates/style.css +0 -54
  302. data/lib/rails_generator/generators/components/scaffold/templates/view_edit.html.erb +0 -18
  303. data/lib/rails_generator/generators/components/scaffold/templates/view_index.html.erb +0 -24
  304. data/lib/rails_generator/generators/components/scaffold/templates/view_new.html.erb +0 -17
  305. data/lib/rails_generator/generators/components/scaffold/templates/view_show.html.erb +0 -10
  306. data/lib/rails_generator/generators/components/session_migration/USAGE +0 -10
  307. data/lib/rails_generator/generators/components/session_migration/session_migration_generator.rb +0 -18
  308. data/lib/rails_generator/generators/components/session_migration/templates/migration.rb +0 -16
  309. data/lib/rails_generator/lookup.rb +0 -249
  310. data/lib/rails_generator/manifest.rb +0 -53
  311. data/lib/rails_generator/options.rb +0 -150
  312. data/lib/rails_generator/scripts.rb +0 -89
  313. data/lib/rails_generator/scripts/destroy.rb +0 -29
  314. data/lib/rails_generator/scripts/generate.rb +0 -7
  315. data/lib/rails_generator/scripts/update.rb +0 -12
  316. data/lib/rails_generator/secret_key_generator.rb +0 -22
  317. data/lib/rails_generator/simple_logger.rb +0 -46
  318. data/lib/rails_generator/spec.rb +0 -44
  319. data/lib/railties_path.rb +0 -1
  320. data/lib/ruby_version_check.rb +0 -17
  321. data/lib/rubyprof_ext.rb +0 -35
  322. data/lib/source_annotation_extractor.rb +0 -102
  323. data/lib/tasks/annotations.rake +0 -20
  324. data/lib/tasks/databases.rake +0 -416
  325. data/lib/tasks/documentation.rake +0 -95
  326. data/lib/tasks/framework.rake +0 -118
  327. data/lib/tasks/gems.rake +0 -80
  328. data/lib/tasks/log.rake +0 -9
  329. data/lib/tasks/misc.rake +0 -56
  330. data/lib/tasks/rails.rb +0 -8
  331. data/lib/tasks/routes.rake +0 -17
  332. data/lib/tasks/statistics.rake +0 -18
  333. data/lib/tasks/testing.rake +0 -139
  334. data/lib/tasks/tmp.rake +0 -37
  335. data/lib/test_help.rb +0 -27
  336. data/lib/webrick_server.rb +0 -156
@@ -1,404 +0,0 @@
1
- Active Record Validations and Callbacks
2
- =======================================
3
-
4
- This guide teaches you how to work with the lifecycle of your Active Record objects. More precisely, you will learn how to validate the state of your objects before they go into the database and also how to teach them to perform custom operations at certain points of their lifecycles.
5
-
6
- After reading this guide and trying out the presented concepts, we hope that you'll be able to:
7
-
8
- * Correctly use all the built-in Active Record validation helpers
9
- * Create your own custom validation methods
10
- * Work with the error messages generated by the validation proccess
11
- * Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved.
12
- * Create special classes that encapsulate common behaviour for your callbacks
13
- * Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations.
14
-
15
- == Motivations to validate your Active Record objects
16
-
17
- The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.
18
-
19
- There are several ways to validate the data that goes to the database, like using database native constraints, implementing validations only at the client side or implementing them directly into your models. Each one has pros and cons:
20
-
21
- * Using database constraints and/or stored procedures makes the validation mechanisms database-dependent and may turn your application into a hard to test and mantain beast. However, if your database is used by other applications, it may be a good idea to use some constraints also at the database level.
22
- * Implementing validations only at the client side can be problematic, specially with web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data.
23
- * Using validation directly into your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the hability to easily create validations, using several built-in helpers while still allowing you to create your own validation methods.
24
-
25
- == How it works
26
-
27
- === When does validation happens?
28
-
29
- There are two kinds of Active Record objects: those that correspond to a row inside your database and those who do not. When you create a fresh object, using the +new+ method, that object does not belong to the database yet. Once you call +save+ upon that object it'll be recorded to it's table. Active Record uses the +new_record?+ instance method to discover if an object is already in the database or not. Consider the following simple and very creative Active Record class:
30
-
31
- [source, ruby]
32
- ------------------------------------------------------------------
33
- class Person < ActiveRecord::Base
34
- end
35
- ------------------------------------------------------------------
36
-
37
- We can see how it works by looking at the following script/console output:
38
-
39
- ------------------------------------------------------------------
40
- >> p = Person.new(:name => "John Doe", :birthdate => Date.parse("09/03/1979"))
41
- => #<Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil, updated_at: nil>
42
- >> p.new_record?
43
- => true
44
- >> p.save
45
- => true
46
- >> p.new_record?
47
- => false
48
- ------------------------------------------------------------------
49
-
50
- Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+, +update_attribute+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
51
-
52
- === The meaning of 'valid'
53
-
54
- For verifying if an object is valid, Active Record uses the +valid?+ method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the +errors+ instance method. The proccess is really simple: If the +errors+ method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the +errors+ collection.
55
-
56
- == The declarative validation helpers
57
-
58
- Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validations rules that are commonly used in most of the applications that you'll write, so you don't need to recreate it everytime, avoiding code duplication, keeping everything organized and boosting your productivity. Everytime a validation fails, an error message is added to the object's +errors+ collection, this message being associated with the field being validated.
59
-
60
- Each helper accepts an arbitrary number of attributes, received as symbols, so with a single line of code you can add the same kind of validation to several attributes.
61
-
62
- All these helpers accept the +:on+ and +:message+ options, which define when the validation should be applied and what message should be added to the +errors+ collection when it fails, respectively. The +:on+ option takes one the values +:save+ (it's the default), +:create+ or +:update+. There is a default error message for each one of the validation helpers. These messages are used when the +:message+ option isn't used. Let's take a look at each one of the available helpers, listed in alphabetic order.
63
-
64
- === The +validates_acceptance_of+ helper
65
-
66
- Validates that a checkbox has been checked for agreement purposes. It's normally used when the user needs to agree with your application's terms of service, confirm reading some clauses or any similar concept. This validation is very specific to web applications and actually this 'acceptance' does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute).
67
-
68
- [source, ruby]
69
- ------------------------------------------------------------------
70
- class Person < ActiveRecord::Base
71
- validates_acceptance_of :terms_of_service
72
- end
73
- ------------------------------------------------------------------
74
-
75
- The default error message for +validates_acceptance_of+ is "_must be accepted_"
76
-
77
- +validates_acceptance_of+ can receive an +:accept+ option, which determines the value that will be considered acceptance. It defaults to "1", but you can change it.
78
-
79
- [source, ruby]
80
- ------------------------------------------------------------------
81
- class Person < ActiveRecord::Base
82
- validates_acceptance_of :terms_of_service, :accept => 'yes'
83
- end
84
- ------------------------------------------------------------------
85
-
86
-
87
- === The +validates_associated+ helper
88
-
89
- You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, +valid?+ will be called upon each one of the associated objects.
90
-
91
- [source, ruby]
92
- ------------------------------------------------------------------
93
- class Library < ActiveRecord::Base
94
- has_many :books
95
- validates_associated :books
96
- end
97
- ------------------------------------------------------------------
98
-
99
- This validation will work with all the association types.
100
-
101
- CAUTION: Pay attention not to use +validates_associated+ on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack.
102
-
103
- The default error message for +validates_associated+ is "_is invalid_". Note that the errors for each failed validation in the associated objects will be set there and not in this model.
104
-
105
- === The +validates_confirmation_of+ helper
106
-
107
- You should use this helper when you have two text fields that should receive exactly the same content, like when you want to confirm an email address or password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with '_confirmation' appended.
108
-
109
- [source, ruby]
110
- ------------------------------------------------------------------
111
- class Person < ActiveRecord::Base
112
- validates_confirmation_of :email
113
- end
114
- ------------------------------------------------------------------
115
-
116
- In your view template you could use something like
117
- ------------------------------------------------------------------
118
- <%= text_field :person, :email %>
119
- <%= text_field :person, :email_confirmation %>
120
- ------------------------------------------------------------------
121
-
122
- NOTE: This check is performed only if +email_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at +validates_presence_of+ later on this guide):
123
-
124
- [source, ruby]
125
- ------------------------------------------------------------------
126
- class Person < ActiveRecord::Base
127
- validates_confirmation_of :email
128
- validates_presence_of :email_confirmation
129
- end
130
- ------------------------------------------------------------------
131
-
132
- The default error message for +validates_confirmation_of+ is "_doesn't match confirmation_"
133
-
134
- === The +validates_each+ helper
135
-
136
- This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to +validates_each+ will be tested against it. In the following example, we don't want names and surnames to begin with lower case.
137
-
138
- [source, ruby]
139
- ------------------------------------------------------------------
140
- class Person < ActiveRecord::Base
141
- validates_each :name, :surname do |model, attr, value|
142
- model.errors.add(attr, 'Must start with upper case') if value =~ /^[a-z]/
143
- end
144
- end
145
- ------------------------------------------------------------------
146
-
147
- The block receives the model, the attribute's name and the attribute's value. If your validation fails, you can add an error message to the model, therefore making it invalid.
148
-
149
- === The +validates_exclusion_of+ helper
150
-
151
- This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.
152
-
153
- [source, ruby]
154
- ------------------------------------------------------------------
155
- class MovieFile < ActiveRecord::Base
156
- validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed"
157
- end
158
- ------------------------------------------------------------------
159
-
160
- The +validates_exclusion_of+ helper has an option +:in+ that receives the set of values that will not be accepted for the validated attributes. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask.
161
-
162
- The default error message for +validates_exclusion_of+ is "_is not included in the list_".
163
-
164
- === The +validates_format_of+ helper
165
-
166
- This helper validates the attributes's values by testing if they match a given pattern. This pattern must be specified using a Ruby regular expression, which must be passed through the +:with+ option.
167
-
168
- [source, ruby]
169
- ------------------------------------------------------------------
170
- class Product < ActiveRecord::Base
171
- validates_format_of :description, :with => /^[a-zA-Z]+$/, :message => "Only letters allowed"
172
- end
173
- ------------------------------------------------------------------
174
-
175
- The default error message for +validates_format_of+ is "_is invalid_".
176
-
177
- === The +validates_inclusion_of+ helper
178
-
179
- This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.
180
-
181
- [source, ruby]
182
- ------------------------------------------------------------------
183
- class Coffee < ActiveRecord::Base
184
- validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size"
185
- end
186
- ------------------------------------------------------------------
187
-
188
- The +validates_inclusion_of+ helper has an option +:in+ that receives the set of values that will be accepted. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask.
189
-
190
- The default error message for +validates_inclusion_of+ is "_is not included in the list_".
191
-
192
- === The +validates_length_of+ helper
193
-
194
- This helper validates the length of your attribute's value. It can receive a variety of different options, so you can specify length contraints in different ways.
195
-
196
- [source, ruby]
197
- ------------------------------------------------------------------
198
- class Person < ActiveRecord::Base
199
- validates_length_of :name, :minimum => 2
200
- validates_length_of :bio, :maximum => 500
201
- validates_length_of :password, :in => 6..20
202
- validates_length_of :registration_number, :is => 6
203
- end
204
- ------------------------------------------------------------------
205
-
206
- The possible length constraint options are:
207
-
208
- * +:minimum+ - The attribute cannot have less than the specified length.
209
- * +:maximum+ - The attribute cannot have more than the specified length.
210
- * +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
211
- * +:is+ - The attribute length must be equal to a given value.
212
-
213
- The default error messages depend on the type of length validation being performed. You can personalize these messages, using the +:wrong_length+, +:too_long+ and +:too_short+ options and the +%d+ format mask as a placeholder for the number corresponding to the length contraint being used. You can still use the +:message+ option to specify an error message.
214
-
215
- [source, ruby]
216
- ------------------------------------------------------------------
217
- class Person < ActiveRecord::Base
218
- validates_length_of :bio, :too_long => "you're writing too much. %d characters is the maximum allowed."
219
- end
220
- ------------------------------------------------------------------
221
-
222
- This helper has an alias called +validates_size_of+, it's the same helper with a different name. You can use it if you'd like to.
223
-
224
- === The +validates_numericallity_of+ helper
225
-
226
- This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the +:integer_only+ option set to true, you can specify that only integral numbers are allowed.
227
-
228
- If you use +:integer_only+ set to +true+, then it will use the +$$/\A[+\-]?\d+\Z/$$+ regular expression to validate the attribute's value. Otherwise, it will try to convert the value using +Kernel.Float+.
229
-
230
- [source, ruby]
231
- ------------------------------------------------------------------
232
- class Player < ActiveRecord::Base
233
- validates_numericallity_of :points
234
- validates_numericallity_of :games_played, :integer_only => true
235
- end
236
- ------------------------------------------------------------------
237
-
238
- The default error message for +validates_numericallity_of+ is "_is not a number_".
239
-
240
- === The +validates_presence_of+ helper
241
-
242
- This helper validates that the attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or an empty string (if the string has only spaces, it will still be considered empty).
243
-
244
- [source, ruby]
245
- ------------------------------------------------------------------
246
- class Person < ActiveRecord::Base
247
- validates_presence_of :name, :login, :email
248
- end
249
- ------------------------------------------------------------------
250
-
251
- NOTE: If you want to be sure that an association is present, you'll need to test if the foreign key used to map the association is present, and not the associated object itself.
252
-
253
- [source, ruby]
254
- ------------------------------------------------------------------
255
- class LineItem < ActiveRecord::Base
256
- belongs_to :order
257
- validates_presence_of :order_id
258
- end
259
- ------------------------------------------------------------------
260
-
261
- NOTE: If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true
262
-
263
- The default error message for +validates_presence_of+ is "_can't be empty_".
264
-
265
- === The +validates_uniqueness_of+ helper
266
-
267
- This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you wish were unique. To avoid that, you must create an unique index in your database.
268
-
269
- [source, ruby]
270
- ------------------------------------------------------------------
271
- class Account < ActiveRecord::Base
272
- validates_uniqueness_of :email
273
- end
274
- ------------------------------------------------------------------
275
-
276
- The validation happens by performing a SQL query into the model's table, searching for a record where the attribute that must be validated is equal to the value in the object being validated.
277
-
278
- There is a +:scope+ option that you can use to specify other attributes that must be used to define uniqueness:
279
-
280
- [source, ruby]
281
- ------------------------------------------------------------------
282
- class Holiday < ActiveRecord::Base
283
- validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year"
284
- end
285
- ------------------------------------------------------------------
286
-
287
- There is also a +:case_sensitive+ option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.
288
-
289
- [source, ruby]
290
- ------------------------------------------------------------------
291
- class Person < ActiveRecord::Base
292
- validates_uniqueness_of :name, :case_sensitive => false
293
- end
294
- ------------------------------------------------------------------
295
-
296
- The default error message for +validates_uniqueness_of+ is "_has already been taken_".
297
-
298
- == Common validation options
299
-
300
- There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which we'll cover right at the next topic.
301
-
302
- === The +:allow_nil+ option
303
-
304
- You may use the +:allow_nil+ option everytime you just want to trigger a validation if the value being validated is not +nil+. You may be asking yourself if it makes any sense to use +:allow_nil+ and +validates_presence_of+ together. Well, it does. Remember, validation will be skipped only for +nil+ attributes, but empty strings are not considered +nil+.
305
-
306
- [source, ruby]
307
- ------------------------------------------------------------------
308
- class Coffee < ActiveRecord::Base
309
- validates_inclusion_of :size, :in => %w(small medium large),
310
- :message => "%s is not a valid size", :allow_nil => true
311
- end
312
- ------------------------------------------------------------------
313
-
314
- === The +:message+ option
315
-
316
- As stated before, the +:message+ option lets you specify the message that will be added to the +errors+ collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.
317
-
318
- === The +:on+ option
319
-
320
- As stated before, the +:on+ option lets you specify when the validation should happen. The default behaviour for all the built-in validation helpers is to be ran on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use +:on =$$>$$ :create+ to run the validation only when a new record is created or +:on =$$>$$ :update+ to run the validation only when a record is updated.
321
-
322
- [source, ruby]
323
- ------------------------------------------------------------------
324
- class Person < ActiveRecord::Base
325
- validates_uniqueness_of :email, :on => :create # => it will be possible to update email with a duplicated value
326
- validates_numericallity_of :age, :on => :update # => it will be possible to create the record with a 'non-numerical age'
327
- validates_presence_of :name, :on => :save # => that's the default
328
- end
329
- ------------------------------------------------------------------
330
-
331
- == Conditional validation
332
-
333
- Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string or a Ruby Proc. You may use the +:if+ option when you want to specify when the validation *should* happen. If you want to specify when the validation *should not* happen, then you may use the +:unless+ option.
334
-
335
- === Using a symbol with the +:if+ and +:unless+ options
336
-
337
- You can associated the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.
338
-
339
- [source, ruby]
340
- ------------------------------------------------------------------
341
- class Order < ActiveRecord::Base
342
- validates_presence_of :card_number, :if => :paid_with_card?
343
-
344
- def paid_with_card?
345
- payment_type == "card"
346
- end
347
- end
348
- ------------------------------------------------------------------
349
-
350
- === Using a string with the +:if+ and +:unless+ options
351
-
352
- You can also use a string that will be evaluated using +:eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.
353
-
354
- [source, ruby]
355
- ------------------------------------------------------------------
356
- class Person < ActiveRecord::Base
357
- validates_presence_of :surname, :if => "name.nil?"
358
- end
359
- ------------------------------------------------------------------
360
-
361
- === Using a Proc object with the +:if+ and :+unless+ options
362
-
363
- Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object which will be called. Using a Proc object can give you the hability to write a condition that will be executed only when the validation happens and not when your code is loaded by the Ruby interpreter. This option is best suited when writing short validation methods, usually one-liners.
364
-
365
- [source, ruby]
366
- ------------------------------------------------------------------
367
- class Account < ActiveRecord::Base
368
- validates_confirmation_of :password, :unless => Proc.new { |a| a.password.blank? }
369
- end
370
- ------------------------------------------------------------------
371
-
372
- == Writing your own validation methods
373
-
374
- When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the +validate+, +validate_on_create+ or +validate_on_update+ methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's +errors+ collection.
375
-
376
- [source, ruby]
377
- ------------------------------------------------------------------
378
- class Invoice < ActiveRecord::Base
379
- def validate_on_create
380
- errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
381
- end
382
- end
383
- ------------------------------------------------------------------
384
-
385
- If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of +validate+, +validate_on_create+ or +validate_on_update+ methods, passing it the symbols for the methods' names.
386
-
387
- [source, ruby]
388
- ------------------------------------------------------------------
389
- class Invoice < ActiveRecord::Base
390
- validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
391
-
392
- def expiration_date_cannot_be_in_the_past
393
- errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
394
- end
395
-
396
- def discount_cannot_be_greater_than_total_value
397
- errors.add(:discount, "can't be greater than total value") unless discount <= total_value
398
- end
399
- end
400
- ------------------------------------------------------------------
401
-
402
- == Changelog
403
-
404
- http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks
@@ -1,1840 +0,0 @@
1
- A Guide to Active Record Associations
2
- =====================================
3
-
4
- This guide covers the association features of Active Record. By referring to this guide, you will be able to:
5
-
6
- * Declare associations between Active Record models
7
- * Understand the various types of Active Record associations
8
- * Use the methods added to your models by creating associations
9
-
10
- == Why Associations?
11
-
12
- 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:
13
-
14
- [source, ruby]
15
- -------------------------------------------------------
16
- class Customer < ActiveRecord::Base
17
- end
18
-
19
- class Order < ActiveRecord::Base
20
- end
21
- -------------------------------------------------------
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
- [source, ruby]
26
- -------------------------------------------------------
27
- @order = Order.create(:order_date => Time.now, :customer_id => @customer.id)
28
- -------------------------------------------------------
29
-
30
- Or consider deleting a customer, and ensuring that all of its orders get deleted as well:
31
-
32
- [source, ruby]
33
- -------------------------------------------------------
34
- @orders = Order.find_by_customer_id(@customer.id)
35
- @orders.each do |order|
36
- order.destroy
37
- end
38
- @customer.destroy
39
- -------------------------------------------------------
40
-
41
- 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:
42
-
43
- [source, ruby]
44
- -------------------------------------------------------
45
- class Customer < ActiveRecord::Base
46
- has_many :orders
47
- end
48
-
49
- class Order < ActiveRecord::Base
50
- belongs_to :customer
51
- end
52
- -------------------------------------------------------
53
-
54
- With this change, creating a new order for a particular customer is easier:
55
-
56
- [source, ruby]
57
- -------------------------------------------------------
58
- @order = @customer.orders.create(:order_date => Time.now)
59
- -------------------------------------------------------
60
-
61
- Deleting a customer and all of its orders is _much_ easier:
62
-
63
- [source, ruby]
64
- -------------------------------------------------------
65
- @customer.destroy
66
- -------------------------------------------------------
67
-
68
- 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.
69
-
70
- == The Types of Associations
71
-
72
- In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key-Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:
73
-
74
- * +belongs_to+
75
- * +has_one+
76
- * +has_many+
77
- * +has_many :through+
78
- * +has_one :through+
79
- * +has_and_belongs_to_many+
80
-
81
- 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.
82
-
83
- === The +belongs_to+ Association
84
-
85
- 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:
86
-
87
- [source, ruby]
88
- -------------------------------------------------------
89
- class Order < ActiveRecord::Base
90
- belongs_to :customer
91
- end
92
- -------------------------------------------------------
93
-
94
- image:images/belongs_to.png[belongs_to Association Diagram]
95
-
96
- === The +has_one+ Association
97
-
98
- 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:
99
-
100
- [source, ruby]
101
- -------------------------------------------------------
102
- class Supplier < ActiveRecord::Base
103
- has_one :account
104
- end
105
- -------------------------------------------------------
106
-
107
- image:images/has_one.png[has_one Association Diagram]
108
-
109
- === The +has_many+ Association
110
-
111
- 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:
112
-
113
- [source, ruby]
114
- -------------------------------------------------------
115
- class Customer < ActiveRecord::Base
116
- has_many :orders
117
- end
118
- -------------------------------------------------------
119
-
120
- NOTE: The name of the other model is pluralized when declaring a +has_many+ association.
121
-
122
- image:images/has_many.png[has_many Association Diagram]
123
-
124
- === The +has_many :through+ Association
125
-
126
- 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:
127
-
128
- [source, ruby]
129
- -------------------------------------------------------
130
- class Physician < ActiveRecord::Base
131
- has_many :appointments
132
- has_many :patients, :through => :appointments
133
- end
134
-
135
- class Appointment < ActiveRecord::Base
136
- belongs_to :physician
137
- belongs_to :patient
138
- end
139
-
140
- class Patient < ActiveRecord::Base
141
- has_many :appointments
142
- has_many :physicians, :through => :appointments
143
- end
144
- -------------------------------------------------------
145
-
146
- image:images/has_many_through.png[has_many :through Association Diagram]
147
-
148
- 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:
149
-
150
- [source, ruby]
151
- -------------------------------------------------------
152
- class Document < ActiveRecord::Base
153
- has_many :sections
154
- has_many :paragraphs, :through => :sections
155
- end
156
-
157
- class Section < ActiveRecord::Base
158
- belongs_to :document
159
- has_many :paragraphs
160
- end
161
-
162
- class Paragraph < ActiveRecord::Base
163
- belongs_to :section
164
- end
165
- -------------------------------------------------------
166
-
167
- === The +has_one :through+ Association
168
-
169
- 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:
170
-
171
- [source, ruby]
172
- -------------------------------------------------------
173
- class Supplier < ActiveRecord::Base
174
- has_one :account
175
- has_one :account_history, :through => :account
176
- end
177
-
178
- class Account < ActiveRecord::Base
179
- belongs_to :supplier
180
- has_one :account_history
181
- end
182
-
183
- class AccountHistory < ActiveRecord::Base
184
- belongs_to :account
185
- end
186
- -------------------------------------------------------
187
-
188
- image:images/has_one_through.png[has_one :through Association Diagram]
189
-
190
- === The +has_and_belongs_to_many+ Association
191
-
192
- 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:
193
-
194
- [source, ruby]
195
- -------------------------------------------------------
196
- class Assembly < ActiveRecord::Base
197
- has_and_belongs_to_many :parts
198
- end
199
-
200
- class Part < ActiveRecord::Base
201
- has_and_belongs_to_many :assemblies
202
- end
203
- -------------------------------------------------------
204
-
205
- image:images/habtm.png[has_and_belongs_to_many Association Diagram]
206
-
207
- === Choosing Between +belongs_to+ and +has_one+
208
-
209
- If you want to set up a 1-1 relationship between two models, you'll need to add +belongs_to+ to one, and +has_one+ to the other. How do you know which is which?
210
-
211
- 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:
212
-
213
- [source, ruby]
214
- -------------------------------------------------------
215
- class Supplier < ActiveRecord::Base
216
- has_one :account
217
- end
218
-
219
- class Account < ActiveRecord::Base
220
- belongs_to :supplier
221
- end
222
- -------------------------------------------------------
223
-
224
- The corresponding migration might look like this:
225
-
226
- [source, ruby]
227
- -------------------------------------------------------
228
- class CreateSuppliers < ActiveRecord::Migration
229
- def self.up
230
- create_table :suppliers do |t|
231
- t.string :name
232
- t.timestamps
233
- end
234
-
235
- create_table :accounts do |t|
236
- t.integer :supplier_id
237
- t.string :account_number
238
- t.timestamps
239
- end
240
- end
241
-
242
- def self.down
243
- drop_table :accounts
244
- drop_table :suppliers
245
- end
246
- end
247
- -------------------------------------------------------
248
-
249
- NOTE: Using +t.integer :supplier_id+ makes the foreign key naming obvious and implicit. In current versions of Rails, you can abstract away this implementation detail by using +t.references :supplier+ instead.
250
-
251
- === Choosing Between +has_many :through+ and +has_and_belongs_to_many+
252
-
253
- 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:
254
-
255
- [source, ruby]
256
- -------------------------------------------------------
257
- class Assembly < ActiveRecord::Base
258
- has_and_belongs_to_many :parts
259
- end
260
-
261
- class Part < ActiveRecord::Base
262
- has_and_belongs_to_many :assemblies
263
- end
264
- -------------------------------------------------------
265
-
266
- 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:
267
-
268
- [source, ruby]
269
- -------------------------------------------------------
270
- class Assembly < ActiveRecord::Base
271
- has_many :manifests
272
- has_many :parts, :through => :manifests
273
- end
274
-
275
- class Manifest < ActiveRecord::Base
276
- belongs_to :assembly
277
- belongs_to :part
278
- end
279
-
280
- class Part < ActiveRecord::Base
281
- has_many :manifests
282
- has_many :assemblies, :through => :manifests
283
- end
284
- -------------------------------------------------------
285
-
286
- 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).
287
-
288
- You should use +has_many :through+ if you need validations, callbacks, or extra attributes on the join model.
289
-
290
- === Polymorphic Associations
291
-
292
- 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:
293
-
294
- [source, ruby]
295
- -------------------------------------------------------
296
- class Picture < ActiveRecord::Base
297
- belongs_to :imageable, :polymorphic => true
298
- end
299
-
300
- class Employee < ActiveRecord::Base
301
- has_many :pictures, :as => :imageable
302
- end
303
-
304
- class Product < ActiveRecord::Base
305
- has_many :pictures, :as => :imageable
306
- end
307
- -------------------------------------------------------
308
-
309
- 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+. Similarly, you can retrieve +@product.pictures+. 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:
310
-
311
- [source, ruby]
312
- -------------------------------------------------------
313
- class CreatePictures < ActiveRecord::Migration
314
- def self.up
315
- create_table :pictures do |t|
316
- t.string :name
317
- t.integer :imageable_id
318
- t.string :imageable_type
319
- t.timestamps
320
- end
321
- end
322
-
323
- def self.down
324
- drop_table :pictures
325
- end
326
- end
327
- -------------------------------------------------------
328
-
329
- This migration can be simplified by using the +t.references+ form:
330
-
331
- [source, ruby]
332
- -------------------------------------------------------
333
- class CreatePictures < ActiveRecord::Migration
334
- def self.up
335
- create_table :pictures do |t|
336
- t.string :name
337
- t.references :imageable, :polymorphic => true
338
- t.timestamps
339
- end
340
- end
341
-
342
- def self.down
343
- drop_table :pictures
344
- end
345
- end
346
- -------------------------------------------------------
347
-
348
- image:images/polymorphic.png[Polymorphic Association Diagram]
349
-
350
- === Self Joins
351
-
352
- 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 manager and subordinates. This situation can be modeled with self-joining associations:
353
-
354
- [source, ruby]
355
- -------------------------------------------------------
356
- class Employee < ActiveRecord::Base
357
- has_many :subordinates, :class_name => "User", :foreign_key => "manager_id"
358
- belongs_to :manager, :class_name => "User"
359
- end
360
- -------------------------------------------------------
361
-
362
- With this setup, you can retrieve +@employee.subordinates+ and +@employee.manager+.
363
-
364
- == Tips, Tricks, and Warnings
365
-
366
- Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
367
-
368
- * Controlling caching
369
- * Avoiding name collisions
370
- * Updating the schema
371
- * Controlling association scope
372
-
373
- === Controlling Caching
374
-
375
- All of the association methods are built around caching that keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:
376
-
377
- [source, ruby]
378
- -------------------------------------------------------
379
- customer.orders # retrieves orders from the database
380
- customer.orders.size # uses the cached copy of orders
381
- customer.orders.empty? # uses the cached copy of orders
382
- -------------------------------------------------------
383
-
384
- 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:
385
-
386
- [source, ruby]
387
- -------------------------------------------------------
388
- customer.orders # retrieves orders from the database
389
- customer.orders.size # uses the cached copy of orders
390
- customer.orders(true).empty? # discards the cached copy of orders and goes back to the database
391
- -------------------------------------------------------
392
-
393
- === Avoiding Name Collisions
394
-
395
- 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.
396
-
397
- === Updating the Schema
398
-
399
- 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. First, you need to create foreign keys as appropriate:
400
-
401
- [source, ruby]
402
- -------------------------------------------------------
403
- class Order < ActiveRecord::Base
404
- belongs_to :customer
405
- end
406
- -------------------------------------------------------
407
-
408
- This declaration needs to be backed up by the proper foreign key declaration on the orders table:
409
-
410
- [source, ruby]
411
- -------------------------------------------------------
412
- class CreateOrders < ActiveRecord::Migration
413
- def self.up
414
- create_table :orders do |t|
415
- t.order_date :datetime
416
- t.order_number :string
417
- t.customer_id :integer
418
- end
419
- end
420
-
421
- def self.down
422
- drop_table :orders
423
- end
424
- end
425
- -------------------------------------------------------
426
-
427
- 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.
428
-
429
- Second, 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 create 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.
430
-
431
- WARNING: The precedence between model names is calculated using the +<+ operator for +String+. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers".
432
-
433
- Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
434
-
435
- [source, ruby]
436
- -------------------------------------------------------
437
- class Assembly < ActiveRecord::Base
438
- has_and_belongs_to_many :parts
439
- end
440
-
441
- class Part < ActiveRecord::Base
442
- has_and_belongs_to_many :assemblies
443
- end
444
- -------------------------------------------------------
445
-
446
- These need to be backed up by a migration to create the +assemblies_parts+ table. This table should be created without a primary key:
447
-
448
- [source, ruby]
449
- -------------------------------------------------------
450
- class CreateAssemblyPartJoinTable < ActiveRecord::Migration
451
- def self.up
452
- create_table :assemblies_parts, :id => false do |t|
453
- t.integer :assembly_id
454
- t.integer :part_id
455
- end
456
- end
457
-
458
- def self.down
459
- drop_table :assemblies_parts
460
- end
461
- end
462
- -------------------------------------------------------
463
-
464
- === Controlling Association Scope
465
-
466
- 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:
467
-
468
- [source, ruby]
469
- -------------------------------------------------------
470
- module MyApplication
471
- module Business
472
- class Supplier < ActiveRecord::Base
473
- has_one :account
474
- end
475
-
476
- class Account < ActiveRecord::Base
477
- belongs_to :supplier
478
- end
479
- end
480
- end
481
- -------------------------------------------------------
482
-
483
- This will work fine, because both the +Supplier+ and the +Account+ class are defined within the same scope. But this will not work, because +Supplier+ and +Account+ are defined in different scopes:
484
-
485
- [source, ruby]
486
- -------------------------------------------------------
487
- module MyApplication
488
- module Business
489
- class Supplier < ActiveRecord::Base
490
- has_one :account
491
- end
492
- end
493
-
494
- module Billing
495
- class Account < ActiveRecord::Base
496
- belongs_to :supplier
497
- end
498
- end
499
- end
500
- -------------------------------------------------------
501
-
502
- To associate a model with a model in a different scope, you must specify the complete class name in your association declaration:
503
-
504
- [source, ruby]
505
- -------------------------------------------------------
506
- module MyApplication
507
- module Business
508
- class Supplier < ActiveRecord::Base
509
- has_one :account, :class_name => "MyApplication::Billing::Account"
510
- end
511
- end
512
-
513
- module Billing
514
- class Account < ActiveRecord::Base
515
- belongs_to :supplier, :class_name => "MyApplication::Business::Supplier"
516
- end
517
- end
518
- end
519
- -------------------------------------------------------
520
-
521
- == Detailed Association Reference
522
-
523
- 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.
524
-
525
- === The +belongs_to+ Association
526
-
527
- 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.
528
-
529
- ==== Methods Added by +belongs_to+
530
-
531
- When you declare a +belongs_to+ assocation, the declaring class automatically gains five methods related to the association:
532
-
533
- * +_association_(force_reload = false)+
534
- * +_association_=(associate)+
535
- * +_association_.nil?+
536
- * +build___association__(attributes = {})+
537
- * +create___association__(attributes = {})+
538
-
539
- In all of these methods, +_association_+ is replaced with the symbol passed as the first argument to +belongs_to+. For example, given the declaration:
540
-
541
- [source, ruby]
542
- -------------------------------------------------------
543
- class Order < ActiveRecord::Base
544
- belongs_to :customer
545
- end
546
- -------------------------------------------------------
547
-
548
- Each instance of the order model will have these methods:
549
-
550
- [source, ruby]
551
- -------------------------------------------------------
552
- customer
553
- customer=
554
- customer.nil?
555
- build_customer
556
- create_customer
557
- -------------------------------------------------------
558
-
559
- ===== +_association_(force_reload = false)+
560
-
561
- The +_association_+ method returns the associated object, if any. If no associated object is found, it returns +nil+.
562
-
563
- [source, ruby]
564
- -------------------------------------------------------
565
- @customer = @order.customer
566
- -------------------------------------------------------
567
-
568
- 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.
569
-
570
- ===== +_association_=(associate)+
571
-
572
- The +_association_=+ 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.
573
-
574
- [source, ruby]
575
- -------------------------------------------------------
576
- @order.customer = @customer
577
- -------------------------------------------------------
578
-
579
- ===== +_association_.nil?+
580
-
581
- The +_association_.nil?+ method returns +true+ if there is no associated object.
582
-
583
- [source, ruby]
584
- -------------------------------------------------------
585
- if @order.customer.nil?
586
- @msg = "No customer found for this order"
587
- end
588
- -------------------------------------------------------
589
-
590
- ===== +build___association__(attributes = {})+
591
-
592
- The +build__\_association__+ 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.
593
-
594
- [source, ruby]
595
- -------------------------------------------------------
596
- @customer = @order.build_customer({:customer_number => 123, :customer_name => "John Doe"})
597
- -------------------------------------------------------
598
-
599
- ===== +create___association__(attributes = {})+
600
-
601
- The +create__\_association__+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
602
-
603
- [source, ruby]
604
- -------------------------------------------------------
605
- @customer = @order.create_customer({:customer_number => 123, :customer_name => "John Doe"})
606
- -------------------------------------------------------
607
-
608
- ==== Options for +belongs_to+
609
-
610
- In many situations, you can use the default behavior of +belongs_to+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +belongs_to+ association. For example, an association with several options might look like this:
611
-
612
- [source, ruby]
613
- -------------------------------------------------------
614
- class Order < ActiveRecord::Base
615
- belongs_to :customer, :counter_cache => true, :conditions => "active = 1"
616
- end
617
- -------------------------------------------------------
618
-
619
- The +belongs_to+ association supports these options:
620
-
621
- // * +:accessible+
622
- * +:class_name+
623
- * +:conditions+
624
- * +:counter_cache+
625
- * +:dependent+
626
- * +:foreign_key+
627
- * +:include+
628
- * +:polymorphic+
629
- * +:readonly+
630
- * +:select+
631
- * +:validate+
632
-
633
- // ===== +:accessible+
634
- //
635
- // The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
636
- //
637
- ===== +:class_name+
638
-
639
- 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:
640
-
641
- [source, ruby]
642
- -------------------------------------------------------
643
- class Order < ActiveRecord::Base
644
- belongs_to :customer, :class_name => "Patron"
645
- end
646
- -------------------------------------------------------
647
-
648
- ===== +:conditions+
649
-
650
- The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
651
-
652
- [source, ruby]
653
- -------------------------------------------------------
654
- class Order < ActiveRecord::Base
655
- belongs_to :customer, :conditions => "active = 1"
656
- end
657
- -------------------------------------------------------
658
-
659
- ===== +:counter_cache+
660
-
661
- The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
662
-
663
- [source, ruby]
664
- -------------------------------------------------------
665
- class Order < ActiveRecord::Base
666
- belongs_to :customer
667
- end
668
- class Customer < ActiveRecord::Base
669
- has_many :orders
670
- end
671
- -------------------------------------------------------
672
-
673
- 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:
674
-
675
- [source, ruby]
676
- -------------------------------------------------------
677
- class Order < ActiveRecord::Base
678
- belongs_to :customer, :counter_cache => true
679
- end
680
- class Customer < ActiveRecord::Base
681
- has_many :orders
682
- end
683
- -------------------------------------------------------
684
-
685
- With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +.size+ method.
686
-
687
- 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:
688
-
689
- [source, ruby]
690
- -------------------------------------------------------
691
- class Order < ActiveRecord::Base
692
- belongs_to :customer, :counter_cache => :count_of_orders
693
- end
694
- class Customer < ActiveRecord::Base
695
- has_many :orders
696
- end
697
- -------------------------------------------------------
698
-
699
- Counter cache columns are added to the containing model's list of read-only attributes through +attr_readonly+.
700
-
701
- ===== +:dependent+
702
-
703
- 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.
704
-
705
- 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.
706
-
707
- ===== +:foreign_key+
708
-
709
- By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
710
-
711
- [source, ruby]
712
- -------------------------------------------------------
713
- class Order < ActiveRecord::Base
714
- belongs_to :customer, :class_name => "Patron", :foreign_key => "patron_id"
715
- end
716
- -------------------------------------------------------
717
-
718
- TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
719
-
720
- ===== +:include+
721
-
722
- 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:
723
-
724
- [source, ruby]
725
- -------------------------------------------------------
726
- class LineItem < ActiveRecord::Base
727
- belongs_to :order
728
- end
729
- class Order < ActiveRecord::Base
730
- belongs_to :customer
731
- has_many :line_items
732
- end
733
- class Customer < ActiveRecord::Base
734
- has_many :orders
735
- end
736
- -------------------------------------------------------
737
-
738
- 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:
739
-
740
- [source, ruby]
741
- -------------------------------------------------------
742
- class LineItem < ActiveRecord::Base
743
- belongs_to :order, :include => :customer
744
- end
745
- class Order < ActiveRecord::Base
746
- belongs_to :customer
747
- has_many :line_items
748
- end
749
- class Customer < ActiveRecord::Base
750
- has_many :orders
751
- end
752
- -------------------------------------------------------
753
-
754
- 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.
755
-
756
- ===== +:polymorphic+
757
-
758
- Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.
759
-
760
- ===== +:readonly+
761
-
762
- If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
763
-
764
- ===== +:select+
765
-
766
- 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.
767
-
768
- 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.
769
-
770
- ===== +:validate+
771
-
772
- 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.
773
-
774
- ==== When are Objects Saved?
775
-
776
- Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either.
777
-
778
- === The has_one Association
779
-
780
- 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.
781
-
782
- ==== Methods Added by +has_one+
783
-
784
- When you declare a +has_one+ association, the declaring class automatically gains five methods related to the association:
785
-
786
- * +_association_(force_reload = false)+
787
- * +_association_=(associate)+
788
- * +_association_.nil?+
789
- * +build___association__(attributes = {})+
790
- * +create___association__(attributes = {})+
791
-
792
- In all of these methods, +_association_+ is replaced with the symbol passed as the first argument to +has_one+. For example, given the declaration:
793
-
794
- [source, ruby]
795
- -------------------------------------------------------
796
- class Supplier < ActiveRecord::Base
797
- has_one :account
798
- end
799
- -------------------------------------------------------
800
-
801
- Each instance of the +Supplier+ model will have these methods:
802
-
803
- [source, ruby]
804
- -------------------------------------------------------
805
- account
806
- account=
807
- account.nil?
808
- build_account
809
- create_account
810
- -------------------------------------------------------
811
-
812
- ===== +_association_(force_reload = false)+
813
-
814
- The +_association_+ method returns the associated object, if any. If no associated object is found, it returns +nil+.
815
-
816
- [source, ruby]
817
- -------------------------------------------------------
818
- @account = @supplier.account
819
- -------------------------------------------------------
820
-
821
- 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.
822
-
823
- ===== +_association_=(associate)+
824
-
825
- The +_association_=+ 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.
826
-
827
- [source, ruby]
828
- -------------------------------------------------------
829
- @suppler.account = @account
830
- -------------------------------------------------------
831
-
832
- ===== +_association_.nil?+
833
-
834
- The +_association_.nil?+ method returns +true+ if there is no associated object.
835
-
836
- [source, ruby]
837
- -------------------------------------------------------
838
- if @supplier.account.nil?
839
- @msg = "No account found for this supplier"
840
- end
841
- -------------------------------------------------------
842
-
843
- ===== +build___association__(attributes = {})+
844
-
845
- The +build__\_association__+ 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.
846
-
847
- [source, ruby]
848
- -------------------------------------------------------
849
- @account = @supplier.build_account({:terms => "Net 30"})
850
- -------------------------------------------------------
851
-
852
- ===== +create___association__(attributes = {})+
853
-
854
- The +create__\_association__+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
855
-
856
- [source, ruby]
857
- -------------------------------------------------------
858
- @account = @supplier.create_account({:terms => "Net 30"})
859
- -------------------------------------------------------
860
-
861
- ==== Options for +has_one+
862
-
863
- In many situations, you can use the default behavior of +has_one+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_one+ association. For example, an association with several options might look like this:
864
-
865
- [source, ruby]
866
- -------------------------------------------------------
867
- class Supplier < ActiveRecord::Base
868
- has_one :account, :class_name => "Billing", :dependent => :nullify
869
- end
870
- -------------------------------------------------------
871
-
872
- The +has_one+ association supports these options:
873
-
874
- // * +:accessible+
875
- * +:as+
876
- * +:class_name+
877
- * +:conditions+
878
- * +:dependent+
879
- * +:foreign_key+
880
- * +:include+
881
- * +:order+
882
- * +:primary_key+
883
- * +:readonly+
884
- * +:select+
885
- * +:source+
886
- * +:source_type+
887
- * +:through+
888
- * +:validate+
889
-
890
- // ===== +:accessible+
891
- //
892
- // The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
893
- //
894
- ===== +:as+
895
-
896
- Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
897
-
898
- ===== +:class_name+
899
-
900
- 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:
901
-
902
- [source, ruby]
903
- -------------------------------------------------------
904
- class Supplier < ActiveRecord::Base
905
- has_one :account, :class_name => "Billing"
906
- end
907
- -------------------------------------------------------
908
-
909
- ===== +:conditions+
910
-
911
- The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
912
-
913
- [source, ruby]
914
- -------------------------------------------------------
915
- class Supplier < ActiveRecord::Base
916
- has_one :account, :conditions => "confirmed = 1"
917
- end
918
- -------------------------------------------------------
919
-
920
- ===== +:dependent+
921
-
922
- 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+.
923
-
924
- ===== +:foreign_key+
925
-
926
- By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
927
-
928
- [source, ruby]
929
- -------------------------------------------------------
930
- class Supplier < ActiveRecord::Base
931
- has_one :account, :foreign_key => "supp_id"
932
- end
933
- -------------------------------------------------------
934
-
935
- TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
936
-
937
- ===== +:include+
938
-
939
- 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:
940
-
941
- [source, ruby]
942
- -------------------------------------------------------
943
- class Supplier < ActiveRecord::Base
944
- has_one :account
945
- end
946
- class Account < ActiveRecord::Base
947
- belongs_to :supplier
948
- belongs_to :representative
949
- end
950
- class Representative < ActiveRecord::Base
951
- has_many :accounts
952
- end
953
- -------------------------------------------------------
954
-
955
- 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:
956
-
957
- [source, ruby]
958
- -------------------------------------------------------
959
- class Supplier < ActiveRecord::Base
960
- has_one :account, :include => :representative
961
- end
962
- class Account < ActiveRecord::Base
963
- belongs_to :supplier
964
- belongs_to :representative
965
- end
966
- class Representative < ActiveRecord::Base
967
- has_many :accounts
968
- end
969
- -------------------------------------------------------
970
-
971
- ===== +:order+
972
-
973
- The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
974
-
975
- ===== +:primary_key+
976
-
977
- By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
978
-
979
- ===== +:readonly+
980
-
981
- If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
982
-
983
- ===== +:select+
984
-
985
- 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.
986
-
987
- ===== +:source+
988
-
989
- The +:source+ option specifies the source association name for a +has_one :through+ association.
990
-
991
- ===== +:source_type+
992
-
993
- The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
994
-
995
- ===== +:through+
996
-
997
- The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations are discussed in detail later in this guide.
998
-
999
- ===== +:validate+
1000
-
1001
- 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.
1002
-
1003
- ==== When are Objects Saved?
1004
-
1005
- 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.
1006
-
1007
- If either of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1008
-
1009
- 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.
1010
-
1011
- If you want to assign an object to a +has_one+ association without saving the object, use the +association.build+ method.
1012
-
1013
- === The has_many Association
1014
-
1015
- 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.
1016
-
1017
- ==== Methods Added
1018
-
1019
- When you declare a +has_many+ association, the declaring class automatically gains 13 methods related to the association:
1020
-
1021
- * +_collection_(force_reload = false)+
1022
- * +_collection_<<(object, ...)+
1023
- * +_collection_.delete(object, ...)+
1024
- * +_collection_=objects+
1025
- * +_collection\_singular_\_ids+
1026
- * +_collection\_singular_\_ids=ids+
1027
- * +_collection_.clear+
1028
- * +_collection_.empty?+
1029
- * +_collection_.size+
1030
- * +_collection_.find(...)+
1031
- * +_collection_.exist?(...)+
1032
- * +_collection_.build(attributes = {}, ...)+
1033
- * +_collection_.create(attributes = {})+
1034
-
1035
- In all of these methods, +_collection_+ is replaced with the symbol passed as the first argument to +has_many+, and +_collection\_singular_+ is replaced with the singularized version of that symbol.. For example, given the declaration:
1036
-
1037
- [source, ruby]
1038
- -------------------------------------------------------
1039
- class Customer < ActiveRecord::Base
1040
- has_many :orders
1041
- end
1042
- -------------------------------------------------------
1043
-
1044
- Each instance of the customer model will have these methods:
1045
-
1046
- [source, ruby]
1047
- -------------------------------------------------------
1048
- orders(force_reload = false)
1049
- orders<<(object, ...)
1050
- orders.delete(object, ...)
1051
- orders=objects
1052
- order_ids
1053
- order_ids=ids
1054
- orders.clear
1055
- orders.empty?
1056
- orders.size
1057
- orders.find(...)
1058
- orders.exist?(...)
1059
- orders.build(attributes = {}, ...)
1060
- orders.create(attributes = {})
1061
- -------------------------------------------------------
1062
-
1063
- ===== +_collection_(force_reload = false)+
1064
-
1065
- The +_collection_+ method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
1066
-
1067
- [source, ruby]
1068
- -------------------------------------------------------
1069
- @orders = @customer.orders
1070
- -------------------------------------------------------
1071
-
1072
- ===== +_collection_<<(object, ...)+
1073
-
1074
- The +_collection_<<+ method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
1075
-
1076
- [source, ruby]
1077
- -------------------------------------------------------
1078
- @customer.orders << @order1
1079
- -------------------------------------------------------
1080
-
1081
- ===== +_collection_.delete(object, ...)+
1082
-
1083
- The +_collection_.delete+ method removes one or more objects from the collection by setting their foreign keys to +NULL+.
1084
-
1085
- [source, ruby]
1086
- -------------------------------------------------------
1087
- @customer.orders.delete(@order1)
1088
- -------------------------------------------------------
1089
-
1090
- WARNING: Objects will be in addition destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+.
1091
-
1092
-
1093
- ===== +_collection_=objects+
1094
-
1095
- The +_collection_=+ method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
1096
-
1097
- ===== +_collection\_singular_\_ids+
1098
-
1099
- The +_collection\_singular_\_ids+ method returns an array of the ids of the objects in the collection.
1100
-
1101
- [source, ruby]
1102
- -------------------------------------------------------
1103
- @order_ids = @customer.order_ids
1104
- -------------------------------------------------------
1105
-
1106
- ===== +__collection\_singular_\_ids=ids+
1107
-
1108
- The +__collection\_singular_\_ids=+ method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
1109
-
1110
- ===== +_collection_.clear+
1111
-
1112
- The +_collection_.clear+ 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+.
1113
-
1114
- ===== +_collection_.empty?+
1115
-
1116
- The +_collection_.empty?+ method returns +true+ if the collection does not contain any associated objects.
1117
-
1118
- [source, ruby]
1119
- -------------------------------------------------------
1120
- <% if @customer.orders.empty? %>
1121
- No Orders Found
1122
- <% end %>
1123
- -------------------------------------------------------
1124
-
1125
- ===== +_collection_.size+
1126
-
1127
- The +_collection_.size+ method returns the number of objects in the collection.
1128
-
1129
- [source, ruby]
1130
- -------------------------------------------------------
1131
- @order_count = @customer.orders.size
1132
- -------------------------------------------------------
1133
-
1134
- ===== +_collection_.find(...)+
1135
-
1136
- The +_collection_.find+ method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
1137
-
1138
- [source, ruby]
1139
- -------------------------------------------------------
1140
- @open_orders = @customer.orders.find(:all, :conditions => "open = 1")
1141
- -------------------------------------------------------
1142
-
1143
- ===== +_collection_.exist?(...)+
1144
-
1145
- The +_collection_.exist?+ method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
1146
-
1147
- ===== +_collection_.build(attributes = {}, ...)+
1148
-
1149
- The +_collection_.build+ 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.
1150
-
1151
- [source, ruby]
1152
- -------------------------------------------------------
1153
- @order = @customer.orders.build({:order_date => Time.now, :order_number => "A12345"})
1154
- -------------------------------------------------------
1155
-
1156
- ===== +_collection_.create(attributes = {})+
1157
-
1158
- The +_collection_.create+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object _will_ be saved (assuming that it passes any validations).
1159
-
1160
- [source, ruby]
1161
- -------------------------------------------------------
1162
- @order = @customer.orders.create({:order_date => Time.now, :order_number => "A12345"})
1163
- -------------------------------------------------------
1164
-
1165
- ==== Options for has_many
1166
-
1167
- In many situations, you can use the default behavior for +has_many+ without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_many+ association. For example, an association with several options might look like this:
1168
-
1169
- [source, ruby]
1170
- -------------------------------------------------------
1171
- class Customer < ActiveRecord::Base
1172
- has_many :orders, :dependent => :delete_all, :validate => :false
1173
- end
1174
- -------------------------------------------------------
1175
-
1176
- The +has_many+ association supports these options:
1177
-
1178
- // * +:accessible+
1179
- * +:as+
1180
- * +:class_name+
1181
- * +:conditions+
1182
- * +:counter_sql+
1183
- * +:dependent+
1184
- * +:extend+
1185
- * +:finder_sql+
1186
- * +:foreign_key+
1187
- * +:group+
1188
- * +:include+
1189
- * +:limit+
1190
- * +:offset+
1191
- * +:order+
1192
- * +:primary_key+
1193
- * +:readonly+
1194
- * +:select+
1195
- * +:source+
1196
- * +:source_type+
1197
- * +:through+
1198
- * +:uniq+
1199
- * +:validate+
1200
-
1201
- // ===== +:accessible+
1202
- //
1203
- // The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
1204
- //
1205
- ===== +:as+
1206
-
1207
- Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide.
1208
-
1209
- ===== +:class_name+
1210
-
1211
- 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:
1212
-
1213
- [source, ruby]
1214
- -------------------------------------------------------
1215
- class Customer < ActiveRecord::Base
1216
- has_many :orders, :class_name => "Transaction"
1217
- end
1218
- -------------------------------------------------------
1219
-
1220
- ===== +:conditions+
1221
-
1222
- The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
1223
-
1224
- [source, ruby]
1225
- -------------------------------------------------------
1226
- class Customer < ActiveRecord::Base
1227
- has_many :confirmed_orders, :class_name => "Order", :conditions => "confirmed = 1"
1228
- end
1229
- -------------------------------------------------------
1230
-
1231
- You can also set conditions via a hash:
1232
-
1233
- [source, ruby]
1234
- -------------------------------------------------------
1235
- class Customer < ActiveRecord::Base
1236
- has_many :confirmed_orders, :class_name => "Order", :conditions => { :confirmed => true }
1237
- end
1238
- -------------------------------------------------------
1239
-
1240
- 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+.
1241
-
1242
- ===== +:counter_sql+
1243
-
1244
- 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.
1245
-
1246
- 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.
1247
-
1248
- ===== +:dependent+
1249
-
1250
- 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+.
1251
-
1252
- NOTE: This option is ignored when you use the +:through+ option on the association.
1253
-
1254
- ===== +:extend+
1255
-
1256
- The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
1257
-
1258
- ===== +:finder_sql+
1259
-
1260
- 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.
1261
-
1262
- ===== +:foreign_key+
1263
-
1264
- By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
1265
-
1266
- [source, ruby]
1267
- -------------------------------------------------------
1268
- class Customer < ActiveRecord::Base
1269
- has_many :orders, :foreign_key => "cust_id"
1270
- end
1271
- -------------------------------------------------------
1272
-
1273
- TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
1274
-
1275
- ===== +:group+
1276
-
1277
- The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
1278
-
1279
- [source, ruby]
1280
- -------------------------------------------------------
1281
- class Customer < ActiveRecord::Base
1282
- has_many :line_items, :through => :orders, :group => "orders.id"
1283
- end
1284
- -------------------------------------------------------
1285
-
1286
- ===== +:include+
1287
-
1288
- 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:
1289
-
1290
- [source, ruby]
1291
- -------------------------------------------------------
1292
- class Customer < ActiveRecord::Base
1293
- has_many :orders
1294
- end
1295
- class Order < ActiveRecord::Base
1296
- belongs_to :customer
1297
- has_many :line_items
1298
- end
1299
- class LineItem < ActiveRecord::Base
1300
- belongs_to :order
1301
- end
1302
- -------------------------------------------------------
1303
-
1304
- 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:
1305
-
1306
- [source, ruby]
1307
- -------------------------------------------------------
1308
- class Customer < ActiveRecord::Base
1309
- has_many :orders, :include => :line_items
1310
- end
1311
- class Order < ActiveRecord::Base
1312
- belongs_to :customer
1313
- has_many :line_items
1314
- end
1315
- class LineItem < ActiveRecord::Base
1316
- belongs_to :order
1317
- end
1318
- -------------------------------------------------------
1319
-
1320
- ===== +:limit+
1321
-
1322
- The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
1323
-
1324
- [source, ruby]
1325
- -------------------------------------------------------
1326
- class Customer < ActiveRecord::Base
1327
- has_many :recent_orders, :class_name => "Order", :order => "order_date DESC", :limit => 100
1328
- end
1329
- -------------------------------------------------------
1330
-
1331
- ===== +:offset+
1332
-
1333
- 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 10 records.
1334
-
1335
- ===== +:order+
1336
-
1337
- The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
1338
-
1339
- [source, ruby]
1340
- -------------------------------------------------------
1341
- class Customer < ActiveRecord::Base
1342
- has_many :orders, :order => "date_confirmed DESC"
1343
- end
1344
- -------------------------------------------------------
1345
-
1346
- ===== +:primary_key+
1347
-
1348
- By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
1349
-
1350
- ===== +:readonly+
1351
-
1352
- If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
1353
-
1354
- ===== +:select+
1355
-
1356
- 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.
1357
-
1358
- 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.
1359
-
1360
- ===== +:source+
1361
-
1362
- 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.
1363
-
1364
- ===== +:source_type+
1365
-
1366
- The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
1367
-
1368
- ===== +:through+
1369
-
1370
- 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 earlier in this guide.
1371
-
1372
- ===== +:uniq+
1373
-
1374
- Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
1375
-
1376
- ===== +:validate+
1377
-
1378
- 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.
1379
-
1380
- ==== When are Objects Saved?
1381
-
1382
- 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.
1383
-
1384
- If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1385
-
1386
- 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.
1387
-
1388
- If you want to assign an object to a +has_many+ association without saving the object, use the +_collection_.build+ method.
1389
-
1390
- === The +has_and_belongs_to_many+ Association
1391
-
1392
- 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.
1393
-
1394
- ==== Methods Added
1395
-
1396
- When you declare a +has_and_belongs_to_many+ association, the declaring class automatically gains 13 methods related to the association:
1397
-
1398
- * +_collection_(force_reload = false)+
1399
- * +_collection_<<(object, ...)+
1400
- * +_collection_.delete(object, ...)+
1401
- * +_collection_=objects+
1402
- * +_collection\_singular_\_ids+
1403
- * +_collection\_singular_\_ids=ids+
1404
- * +_collection_.clear+
1405
- * +_collection_.empty?+
1406
- * +_collection_.size+
1407
- * +_collection_.find(...)+
1408
- * +_collection_.exist?(...)+
1409
- * +_collection_.build(attributes = {})+
1410
- * +_collection_.create(attributes = {})+
1411
-
1412
- In all of these methods, +_collection_+ is replaced with the symbol passed as the first argument to +has_many+, and +_collection_\_singular+ is replaced with the singularized version of that symbol.. For example, given the declaration:
1413
-
1414
- [source, ruby]
1415
- -------------------------------------------------------
1416
- class Part < ActiveRecord::Base
1417
- has_and_belongs_to_many :assemblies
1418
- end
1419
- -------------------------------------------------------
1420
-
1421
- Each instance of the part model will have these methods:
1422
-
1423
- [source, ruby]
1424
- -------------------------------------------------------
1425
- assemblies(force_reload = false)
1426
- assemblies<<(object, ...)
1427
- assemblies.delete(object, ...)
1428
- assemblies=objects
1429
- assembly_ids
1430
- assembly_ids=ids
1431
- assemblies.clear
1432
- assemblies.empty?
1433
- assemblies.size
1434
- assemblies.find(...)
1435
- assemblies.exist?(...)
1436
- assemblies.build(attributes = {}, ...)
1437
- assemblies.create(attributes = {})
1438
- -------------------------------------------------------
1439
-
1440
- ===== Additional Column Methods
1441
-
1442
- 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.
1443
-
1444
- 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+.
1445
-
1446
-
1447
- ===== +_collection_(force_reload = false)+
1448
-
1449
- The +_collection_+ method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
1450
-
1451
- [source, ruby]
1452
- -------------------------------------------------------
1453
- @assemblies = @part.assemblies
1454
- -------------------------------------------------------
1455
-
1456
- ===== +_collection_<<(object, ...)+
1457
-
1458
- The +_collection_<<+ method adds one or more objects to the collection by creating records in the join table.
1459
-
1460
- [source, ruby]
1461
- -------------------------------------------------------
1462
- @part.assemblies << @assembly1
1463
- -------------------------------------------------------
1464
-
1465
- NOTE: This method is aliased as +_collection_.concat+ and +_collection_.push+.
1466
-
1467
- ===== +_collection_.delete(object, ...)+
1468
-
1469
- The +_collection_.delete+ method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
1470
-
1471
- [source, ruby]
1472
- -------------------------------------------------------
1473
- @part.assemblies.delete(@assembly1)
1474
- -------------------------------------------------------
1475
-
1476
- ===== +_collection_=objects+
1477
-
1478
- The +_collection_=+ method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
1479
-
1480
- ===== +_collection\_singular_\_ids+
1481
-
1482
- # Returns an array of the associated objects' ids
1483
-
1484
- The +_collection\_singular_\_ids+ method returns an array of the ids of the objects in the collection.
1485
-
1486
- [source, ruby]
1487
- -------------------------------------------------------
1488
- @assembly_ids = @part.assembly_ids
1489
- -------------------------------------------------------
1490
-
1491
- ===== +_collection\_singular_\_ids=ids+
1492
-
1493
- The +_collection\_singular_\_ids=+ method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
1494
-
1495
- ===== +_collection_.clear+
1496
-
1497
- The +_collection_.clear+ method removes every object from the collection by deleting the rows from the joining tableassociation. This does not destroy the associated objects.
1498
-
1499
- ===== +_collection_.empty?+
1500
-
1501
- The +_collection_.empty?+ method returns +true+ if the collection does not contain any associated objects.
1502
-
1503
- [source, ruby]
1504
- -------------------------------------------------------
1505
- <% if @part.assemblies.empty? %>
1506
- This part is not used in any assemblies
1507
- <% end %>
1508
- -------------------------------------------------------
1509
-
1510
- ===== +_collection_.size+
1511
-
1512
- The +_collection_.size+ method returns the number of objects in the collection.
1513
-
1514
- [source, ruby]
1515
- -------------------------------------------------------
1516
- @assembly_count = @part.assemblies.size
1517
- -------------------------------------------------------
1518
-
1519
- ===== +_collection_.find(...)+
1520
-
1521
- The +_collection_.find+ 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.
1522
-
1523
- [source, ruby]
1524
- -------------------------------------------------------
1525
- @new_assemblies = @part.assemblies.find(:all, :conditions => ["created_at > ?", 2.days.ago])
1526
- -------------------------------------------------------
1527
-
1528
- ===== +_collection_.exist?(...)+
1529
-
1530
- The +_collection_.exist?+ method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
1531
-
1532
- ===== +_collection_.build(attributes = {})+
1533
-
1534
- The +_collection_.build+ 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.
1535
-
1536
- [source, ruby]
1537
- -------------------------------------------------------
1538
- @assembly = @part.assemblies.build({:assembly_name => "Transmission housing"})
1539
- -------------------------------------------------------
1540
-
1541
- ===== +_collection_.create(attributes = {})+
1542
-
1543
- The +_collection_.create+ method returns a new object of the associated type. This objects will be instantiated from the passed attributes, the link through the join table will be created, and the associated object _will_ be saved (assuming that it passes any validations).
1544
-
1545
- [source, ruby]
1546
- -------------------------------------------------------
1547
- @assembly = @part.assemblies.create({:assembly_name => "Transmission housing"})
1548
- -------------------------------------------------------
1549
-
1550
- ==== Options for has_and_belongs_to_many
1551
-
1552
- In many situations, you can use the default behavior for +has_and_belongs_to_many+ without any customization. But you can alter that behavior in a number of ways. This section cover the options that you can pass when you create a +has_and_belongs_to_many+ association. For example, an association with several options might look like this:
1553
-
1554
- [source, ruby]
1555
- -------------------------------------------------------
1556
- class Parts < ActiveRecord::Base
1557
- has_and_belongs_to_many :assemblies, :uniq => true, :read_only => true
1558
- end
1559
- -------------------------------------------------------
1560
-
1561
- The +has_and_belongs_to_many+ association supports these options:
1562
-
1563
- // * +:accessible+
1564
- * +:association_foreign_key+
1565
- * +:class_name+
1566
- * +:conditions+
1567
- * +:counter_sql+
1568
- * +:delete_sql+
1569
- * +:extend+
1570
- * +:finder_sql+
1571
- * +:foreign_key+
1572
- * +:group+
1573
- * +:include+
1574
- * +:insert_sql+
1575
- * +:join_table+
1576
- * +:limit+
1577
- * +:offset+
1578
- * +:order+
1579
- * +:readonly+
1580
- * +:select+
1581
- * +:uniq+
1582
- * +:validate+
1583
-
1584
- // ===== +:accessible+
1585
- //
1586
- // The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
1587
- //
1588
- ===== +:association_foreign_key+
1589
-
1590
- By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly:
1591
-
1592
- TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when setting up a many-to-many self-join. For example:
1593
-
1594
- [source, ruby]
1595
- -------------------------------------------------------
1596
- class User < ActiveRecord::Base
1597
- has_and_belongs_to_many :friends, :class_name => "User",
1598
- :foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
1599
- end
1600
- -------------------------------------------------------
1601
-
1602
- ===== +:class_name+
1603
-
1604
- 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:
1605
-
1606
- [source, ruby]
1607
- -------------------------------------------------------
1608
- class Parts < ActiveRecord::Base
1609
- has_and_belongs_to_many :assemblies, :class_name => "Gadget"
1610
- end
1611
- -------------------------------------------------------
1612
-
1613
- ===== +:conditions+
1614
-
1615
- The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
1616
-
1617
- [source, ruby]
1618
- -------------------------------------------------------
1619
- class Parts < ActiveRecord::Base
1620
- has_and_belongs_to_many :assemblies, :conditions => "factory = 'Seattle'"
1621
- end
1622
- -------------------------------------------------------
1623
-
1624
- You can also set conditions via a hash:
1625
-
1626
- [source, ruby]
1627
- -------------------------------------------------------
1628
- class Parts < ActiveRecord::Base
1629
- has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' }
1630
- end
1631
- -------------------------------------------------------
1632
-
1633
- 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".
1634
-
1635
- ===== +:counter_sql+
1636
-
1637
- 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.
1638
-
1639
- 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.
1640
-
1641
- ===== +:delete_sql+
1642
-
1643
- 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.
1644
-
1645
- ===== +:extend+
1646
-
1647
- The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
1648
-
1649
- ===== +:finder_sql+
1650
-
1651
- 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.
1652
-
1653
- ===== +:foreign_key+
1654
-
1655
- By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
1656
-
1657
- [source, ruby]
1658
- -------------------------------------------------------
1659
- class User < ActiveRecord::Base
1660
- has_and_belongs_to_many :friends, :class_name => "User",
1661
- :foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
1662
- end
1663
- -------------------------------------------------------
1664
-
1665
- ===== +:group+
1666
-
1667
- The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
1668
-
1669
- [source, ruby]
1670
- -------------------------------------------------------
1671
- class Parts < ActiveRecord::Base
1672
- has_and_belongs_to_many :assemblies, :group => "factory"
1673
- end
1674
- -------------------------------------------------------
1675
-
1676
- ===== +:include+
1677
-
1678
- You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
1679
-
1680
- ===== +:insert_sql+
1681
-
1682
- 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.
1683
-
1684
- ===== +:join_table+
1685
-
1686
- 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.
1687
-
1688
- ===== +:limit+
1689
-
1690
- The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
1691
-
1692
- [source, ruby]
1693
- -------------------------------------------------------
1694
- class Parts < ActiveRecord::Base
1695
- has_and_belongs_to_many :assemblies, :order => "created_at DESC", :limit => 50
1696
- end
1697
- -------------------------------------------------------
1698
-
1699
- ===== +:offset+
1700
-
1701
- 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 10 records.
1702
-
1703
- ===== +:order+
1704
-
1705
- The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
1706
-
1707
- [source, ruby]
1708
- -------------------------------------------------------
1709
- class Parts < ActiveRecord::Base
1710
- has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
1711
- end
1712
- -------------------------------------------------------
1713
-
1714
- ===== +:readonly+
1715
-
1716
- If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
1717
-
1718
- ===== +:select+
1719
-
1720
- 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.
1721
-
1722
- ===== +:uniq+
1723
-
1724
- Specify the +:uniq => true+ option to remove duplicates from the collection.
1725
-
1726
- ===== +:validate+
1727
-
1728
- 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.
1729
-
1730
- ==== When are Objects Saved?
1731
-
1732
- 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.
1733
-
1734
- If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
1735
-
1736
- 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.
1737
-
1738
- If you want to assign an object to a +has_and_belongs_to_many+ association without saving the object, use the +_collection_.build+ method.
1739
-
1740
- === Association Callbacks
1741
-
1742
- Normal callbacks hook into the lifecycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a +:before_save+ callback to cause something to happen just before an object is saved.
1743
-
1744
- Association callbacks are similar to normal callbacks, but they are triggered by events in the lifecycle of a collection. There are four available association callbacks:
1745
-
1746
- * +before_add+
1747
- * +after_add+
1748
- * +before_remove+
1749
- * +after_remove+
1750
-
1751
- You define association callbacks by adding options to the association declaration. For example:
1752
-
1753
- [source, ruby]
1754
- -------------------------------------------------------
1755
- class Customer < ActiveRecord::Base
1756
- has_many :orders, :before_add => :check_credit_limit
1757
-
1758
- def check_credit_limit(order)
1759
- ...
1760
- end
1761
- end
1762
- -------------------------------------------------------
1763
-
1764
- Rails passes the object being added or removed to the callback.
1765
-
1766
- You can stack callbacks on a single event by passing them as an array:
1767
-
1768
- [source, ruby]
1769
- -------------------------------------------------------
1770
- class Customer < ActiveRecord::Base
1771
- has_many :orders, :before_add => [:check_credit_limit, :calculate_shipping_charges]
1772
-
1773
- def check_credit_limit(order)
1774
- ...
1775
- end
1776
-
1777
- def calculate_shipping_charges(order)
1778
- ...
1779
- end
1780
- end
1781
- -------------------------------------------------------
1782
-
1783
- 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.
1784
-
1785
- === Association Extensions
1786
-
1787
- 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:
1788
-
1789
- [source, ruby]
1790
- -------------------------------------------------------
1791
- class Customer < ActiveRecord::Base
1792
- has_many :orders do
1793
- def find_by_order_prefix(order_number)
1794
- find_by_region_id(order_number[0..2])
1795
- end
1796
- end
1797
- end
1798
- -------------------------------------------------------
1799
-
1800
- If you have an extension that should be shared by many associations, you can use a named extension module. For example:
1801
-
1802
- [source, ruby]
1803
- -------------------------------------------------------
1804
- module FindRecentExtension
1805
- def find_recent
1806
- find(:all, :conditions => ["created_at > ?", 5.days.ago])
1807
- end
1808
- end
1809
-
1810
- class Customer < ActiveRecord::Base
1811
- has_many :orders, :extend => FindRecentExtension
1812
- end
1813
-
1814
- class Supplier < ActiveRecord::Base
1815
- has_many :deliveries, :extend => FindRecentExtension
1816
- end
1817
- -------------------------------------------------------
1818
-
1819
- To include more than one extension module in a single association, specify an array of names:
1820
-
1821
- [source, ruby]
1822
- -------------------------------------------------------
1823
- class Customer < ActiveRecord::Base
1824
- has_many :orders, :extend => [FindRecentExtension, FindActiveExtension]
1825
- end
1826
- -------------------------------------------------------
1827
-
1828
- Extensions can refer to the internals of the association proxy using these three accessors:
1829
-
1830
- * +proxy_owner+ returns the object that the association is a part of.
1831
- * +proxy_reflection+ returns the reflection object that describes the association.
1832
- * +proxy_target+ returns the associated object for +belongs_to+ or +has_one+, or the collection of associated objects for +has_many+ or +has_and_belongs_to_many+.
1833
-
1834
- == Changelog ==
1835
-
1836
- http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11[Lighthouse ticket]
1837
-
1838
- * September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
1839
- * September 22, 2008: Added diagrams, misc. cleanup by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
1840
- * September 14, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)