railties 3.0.0.beta

Sign up to get free protection for your applications and to get access to all the features.
Files changed (334) hide show
  1. data/CHANGELOG +2201 -0
  2. data/README +286 -0
  3. data/bin/rails +11 -0
  4. data/builtin/rails_info/rails/info.rb +147 -0
  5. data/builtin/rails_info/rails/info_controller.rb +15 -0
  6. data/builtin/rails_info/rails/info_helper.rb +2 -0
  7. data/builtin/routes.rb +3 -0
  8. data/guides/files/javascripts/code_highlighter.js +188 -0
  9. data/guides/files/javascripts/guides.js +7 -0
  10. data/guides/files/javascripts/highlighters.js +90 -0
  11. data/guides/files/stylesheets/main.css +441 -0
  12. data/guides/files/stylesheets/print.css +52 -0
  13. data/guides/files/stylesheets/reset.css +43 -0
  14. data/guides/files/stylesheets/style.css +13 -0
  15. data/guides/files/stylesheets/syntax.css +31 -0
  16. data/guides/images/belongs_to.png +0 -0
  17. data/guides/images/book_icon.gif +0 -0
  18. data/guides/images/bullet.gif +0 -0
  19. data/guides/images/chapters_icon.gif +0 -0
  20. data/guides/images/check_bullet.gif +0 -0
  21. data/guides/images/credits_pic_blank.gif +0 -0
  22. data/guides/images/csrf.png +0 -0
  23. data/guides/images/customized_error_messages.png +0 -0
  24. data/guides/images/error_messages.png +0 -0
  25. data/guides/images/feature_tile.gif +0 -0
  26. data/guides/images/footer_tile.gif +0 -0
  27. data/guides/images/fxn.png +0 -0
  28. data/guides/images/grey_bullet.gif +0 -0
  29. data/guides/images/habtm.png +0 -0
  30. data/guides/images/has_many.png +0 -0
  31. data/guides/images/has_many_through.png +0 -0
  32. data/guides/images/has_one.png +0 -0
  33. data/guides/images/has_one_through.png +0 -0
  34. data/guides/images/header_backdrop.png +0 -0
  35. data/guides/images/header_tile.gif +0 -0
  36. data/guides/images/i18n/demo_localized_pirate.png +0 -0
  37. data/guides/images/i18n/demo_translated_en.png +0 -0
  38. data/guides/images/i18n/demo_translated_pirate.png +0 -0
  39. data/guides/images/i18n/demo_translation_missing.png +0 -0
  40. data/guides/images/i18n/demo_untranslated.png +0 -0
  41. data/guides/images/icons/README +5 -0
  42. data/guides/images/icons/callouts/1.png +0 -0
  43. data/guides/images/icons/callouts/10.png +0 -0
  44. data/guides/images/icons/callouts/11.png +0 -0
  45. data/guides/images/icons/callouts/12.png +0 -0
  46. data/guides/images/icons/callouts/13.png +0 -0
  47. data/guides/images/icons/callouts/14.png +0 -0
  48. data/guides/images/icons/callouts/15.png +0 -0
  49. data/guides/images/icons/callouts/2.png +0 -0
  50. data/guides/images/icons/callouts/3.png +0 -0
  51. data/guides/images/icons/callouts/4.png +0 -0
  52. data/guides/images/icons/callouts/5.png +0 -0
  53. data/guides/images/icons/callouts/6.png +0 -0
  54. data/guides/images/icons/callouts/7.png +0 -0
  55. data/guides/images/icons/callouts/8.png +0 -0
  56. data/guides/images/icons/callouts/9.png +0 -0
  57. data/guides/images/icons/caution.png +0 -0
  58. data/guides/images/icons/example.png +0 -0
  59. data/guides/images/icons/home.png +0 -0
  60. data/guides/images/icons/important.png +0 -0
  61. data/guides/images/icons/next.png +0 -0
  62. data/guides/images/icons/note.png +0 -0
  63. data/guides/images/icons/prev.png +0 -0
  64. data/guides/images/icons/tip.png +0 -0
  65. data/guides/images/icons/up.png +0 -0
  66. data/guides/images/icons/warning.png +0 -0
  67. data/guides/images/nav_arrow.gif +0 -0
  68. data/guides/images/polymorphic.png +0 -0
  69. data/guides/images/posts_index.png +0 -0
  70. data/guides/images/rails_guides_logo.gif +0 -0
  71. data/guides/images/rails_logo_remix.gif +0 -0
  72. data/guides/images/rails_welcome.png +0 -0
  73. data/guides/images/session_fixation.png +0 -0
  74. data/guides/images/tab_grey.gif +0 -0
  75. data/guides/images/tab_info.gif +0 -0
  76. data/guides/images/tab_note.gif +0 -0
  77. data/guides/images/tab_red.gif +0 -0
  78. data/guides/images/tab_yellow.gif +0 -0
  79. data/guides/images/tab_yellow.png +0 -0
  80. data/guides/images/validation_error_messages.png +0 -0
  81. data/guides/rails_guides.rb +44 -0
  82. data/guides/rails_guides/generator.rb +178 -0
  83. data/guides/rails_guides/helpers.rb +34 -0
  84. data/guides/rails_guides/indexer.rb +55 -0
  85. data/guides/rails_guides/levenshtein.rb +31 -0
  86. data/guides/rails_guides/textile_extensions.rb +41 -0
  87. data/guides/source/2_2_release_notes.textile +422 -0
  88. data/guides/source/2_3_release_notes.textile +610 -0
  89. data/guides/source/3_0_release_notes.textile +560 -0
  90. data/guides/source/action_controller_overview.textile +783 -0
  91. data/guides/source/action_mailer_basics.textile +437 -0
  92. data/guides/source/action_view_overview.textile +1481 -0
  93. data/guides/source/active_record_basics.textile +204 -0
  94. data/guides/source/active_record_querying.textile +961 -0
  95. data/guides/source/active_support_core_extensions.textile +1835 -0
  96. data/guides/source/activerecord_validations_callbacks.textile +1127 -0
  97. data/guides/source/ajax_on_rails.textile +342 -0
  98. data/guides/source/association_basics.textile +1816 -0
  99. data/guides/source/caching_with_rails.textile +390 -0
  100. data/guides/source/command_line.textile +589 -0
  101. data/guides/source/configuring.textile +290 -0
  102. data/guides/source/contribute.textile +71 -0
  103. data/guides/source/contributing_to_rails.textile +272 -0
  104. data/guides/source/credits.textile.erb +52 -0
  105. data/guides/source/debugging_rails_applications.textile +709 -0
  106. data/guides/source/form_helpers.textile +768 -0
  107. data/guides/source/generators.textile +378 -0
  108. data/guides/source/getting_started.textile +1310 -0
  109. data/guides/source/i18n.textile +879 -0
  110. data/guides/source/index.textile.erb +124 -0
  111. data/guides/source/layout.html.erb +103 -0
  112. data/guides/source/layouts_and_rendering.textile +979 -0
  113. data/guides/source/migrations.textile +591 -0
  114. data/guides/source/nested_model_forms.textile +222 -0
  115. data/guides/source/performance_testing.textile +531 -0
  116. data/guides/source/plugins.textile +1512 -0
  117. data/guides/source/rails_application_templates.textile +238 -0
  118. data/guides/source/rails_on_rack.textile +306 -0
  119. data/guides/source/routing.textile +903 -0
  120. data/guides/source/security.textile +984 -0
  121. data/guides/source/testing.textile +946 -0
  122. data/lib/generators/erb.rb +8 -0
  123. data/lib/generators/erb/controller/controller_generator.rb +21 -0
  124. data/lib/generators/erb/controller/templates/view.html.erb +2 -0
  125. data/lib/generators/erb/mailer/mailer_generator.rb +20 -0
  126. data/lib/generators/erb/mailer/templates/view.text.erb +3 -0
  127. data/lib/generators/erb/scaffold/scaffold_generator.rb +53 -0
  128. data/lib/generators/erb/scaffold/templates/_form.html.erb +13 -0
  129. data/lib/generators/erb/scaffold/templates/edit.html.erb +6 -0
  130. data/lib/generators/erb/scaffold/templates/index.html.erb +27 -0
  131. data/lib/generators/erb/scaffold/templates/layout.html.erb +16 -0
  132. data/lib/generators/erb/scaffold/templates/new.html.erb +5 -0
  133. data/lib/generators/erb/scaffold/templates/show.html.erb +10 -0
  134. data/lib/generators/rails/app/USAGE +9 -0
  135. data/lib/generators/rails/app/app_generator.rb +262 -0
  136. data/lib/generators/rails/app/templates/Gemfile +34 -0
  137. data/lib/generators/rails/app/templates/README +243 -0
  138. data/lib/generators/rails/app/templates/Rakefile +10 -0
  139. data/lib/generators/rails/app/templates/app/controllers/application_controller.rb +3 -0
  140. data/lib/generators/rails/app/templates/app/helpers/application_helper.rb +2 -0
  141. data/lib/generators/rails/app/templates/app/models/.empty_directory +0 -0
  142. data/lib/generators/rails/app/templates/app/views/layouts/.empty_directory +0 -0
  143. data/lib/generators/rails/app/templates/config.ru +4 -0
  144. data/lib/generators/rails/app/templates/config/application.rb +51 -0
  145. data/lib/generators/rails/app/templates/config/boot.rb +17 -0
  146. data/lib/generators/rails/app/templates/config/databases/frontbase.yml +28 -0
  147. data/lib/generators/rails/app/templates/config/databases/ibm_db.yml +71 -0
  148. data/lib/generators/rails/app/templates/config/databases/mysql.yml +60 -0
  149. data/lib/generators/rails/app/templates/config/databases/oracle.yml +39 -0
  150. data/lib/generators/rails/app/templates/config/databases/postgresql.yml +51 -0
  151. data/lib/generators/rails/app/templates/config/databases/sqlite3.yml +22 -0
  152. data/lib/generators/rails/app/templates/config/environment.rb +5 -0
  153. data/lib/generators/rails/app/templates/config/environments/development.rb.tt +19 -0
  154. data/lib/generators/rails/app/templates/config/environments/production.rb.tt +33 -0
  155. data/lib/generators/rails/app/templates/config/environments/test.rb.tt +29 -0
  156. data/lib/generators/rails/app/templates/config/initializers/backtrace_silencers.rb +7 -0
  157. data/lib/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt +7 -0
  158. data/lib/generators/rails/app/templates/config/initializers/inflections.rb +10 -0
  159. data/lib/generators/rails/app/templates/config/initializers/mime_types.rb +5 -0
  160. data/lib/generators/rails/app/templates/config/initializers/session_store.rb.tt +15 -0
  161. data/lib/generators/rails/app/templates/config/locales/en.yml +5 -0
  162. data/lib/generators/rails/app/templates/config/routes.rb +58 -0
  163. data/lib/generators/rails/app/templates/db/seeds.rb +7 -0
  164. data/lib/generators/rails/app/templates/doc/README_FOR_APP +2 -0
  165. data/lib/generators/rails/app/templates/gitignore +4 -0
  166. data/lib/generators/rails/app/templates/public/404.html +26 -0
  167. data/lib/generators/rails/app/templates/public/422.html +26 -0
  168. data/lib/generators/rails/app/templates/public/500.html +26 -0
  169. data/lib/generators/rails/app/templates/public/favicon.ico +0 -0
  170. data/lib/generators/rails/app/templates/public/images/rails.png +0 -0
  171. data/lib/generators/rails/app/templates/public/index.html +278 -0
  172. data/lib/generators/rails/app/templates/public/javascripts/application.js +2 -0
  173. data/lib/generators/rails/app/templates/public/javascripts/controls.js +963 -0
  174. data/lib/generators/rails/app/templates/public/javascripts/dragdrop.js +973 -0
  175. data/lib/generators/rails/app/templates/public/javascripts/effects.js +1128 -0
  176. data/lib/generators/rails/app/templates/public/javascripts/prototype.js +4320 -0
  177. data/lib/generators/rails/app/templates/public/javascripts/rails.js +110 -0
  178. data/lib/generators/rails/app/templates/public/robots.txt +5 -0
  179. data/lib/generators/rails/app/templates/public/stylesheets/.empty_directory +0 -0
  180. data/lib/generators/rails/app/templates/script/rails +9 -0
  181. data/lib/generators/rails/app/templates/test/fixtures/.empty_directory +0 -0
  182. data/lib/generators/rails/app/templates/test/functional/.empty_directory +0 -0
  183. data/lib/generators/rails/app/templates/test/integration/.empty_directory +0 -0
  184. data/lib/generators/rails/app/templates/test/performance/browsing_test.rb +9 -0
  185. data/lib/generators/rails/app/templates/test/test_helper.rb +13 -0
  186. data/lib/generators/rails/app/templates/test/unit/.empty_directory +0 -0
  187. data/lib/generators/rails/controller/USAGE +18 -0
  188. data/lib/generators/rails/controller/controller_generator.rb +14 -0
  189. data/lib/generators/rails/controller/templates/controller.rb +7 -0
  190. data/lib/generators/rails/generator/USAGE +11 -0
  191. data/lib/generators/rails/generator/generator_generator.rb +25 -0
  192. data/lib/generators/rails/generator/templates/%file_name%_generator.rb.tt +5 -0
  193. data/lib/generators/rails/generator/templates/USAGE.tt +8 -0
  194. data/lib/generators/rails/generator/templates/templates/.empty_directory +0 -0
  195. data/lib/generators/rails/helper/USAGE +17 -0
  196. data/lib/generators/rails/helper/helper_generator.rb +13 -0
  197. data/lib/generators/rails/helper/templates/helper.rb +2 -0
  198. data/lib/generators/rails/integration_test/USAGE +10 -0
  199. data/lib/generators/rails/integration_test/integration_test_generator.rb +7 -0
  200. data/lib/generators/rails/mailer/USAGE +15 -0
  201. data/lib/generators/rails/mailer/mailer_generator.rb +14 -0
  202. data/lib/generators/rails/mailer/templates/mailer.rb +16 -0
  203. data/lib/generators/rails/metal/USAGE +8 -0
  204. data/lib/generators/rails/metal/metal_generator.rb +11 -0
  205. data/lib/generators/rails/metal/templates/metal.rb +12 -0
  206. data/lib/generators/rails/migration/USAGE +29 -0
  207. data/lib/generators/rails/migration/migration_generator.rb +8 -0
  208. data/lib/generators/rails/model/USAGE +30 -0
  209. data/lib/generators/rails/model/model_generator.rb +8 -0
  210. data/lib/generators/rails/model_subclass/model_subclass_generator.rb +12 -0
  211. data/lib/generators/rails/observer/USAGE +12 -0
  212. data/lib/generators/rails/observer/observer_generator.rb +7 -0
  213. data/lib/generators/rails/performance_test/USAGE +10 -0
  214. data/lib/generators/rails/performance_test/performance_test_generator.rb +7 -0
  215. data/lib/generators/rails/plugin/USAGE +13 -0
  216. data/lib/generators/rails/plugin/plugin_generator.rb +47 -0
  217. data/lib/generators/rails/plugin/templates/MIT-LICENSE.tt +20 -0
  218. data/lib/generators/rails/plugin/templates/README.tt +13 -0
  219. data/lib/generators/rails/plugin/templates/Rakefile.tt +10 -0
  220. data/lib/generators/rails/plugin/templates/init.rb +1 -0
  221. data/lib/generators/rails/plugin/templates/install.rb +1 -0
  222. data/lib/generators/rails/plugin/templates/lib/%file_name%.rb.tt +1 -0
  223. data/lib/generators/rails/plugin/templates/lib/tasks/%file_name%_tasks.rake.tt +4 -0
  224. data/lib/generators/rails/plugin/templates/uninstall.rb +1 -0
  225. data/lib/generators/rails/resource/USAGE +23 -0
  226. data/lib/generators/rails/resource/resource_generator.rb +34 -0
  227. data/lib/generators/rails/scaffold/USAGE +29 -0
  228. data/lib/generators/rails/scaffold/scaffold_generator.rb +13 -0
  229. data/lib/generators/rails/scaffold_controller/USAGE +20 -0
  230. data/lib/generators/rails/scaffold_controller/scaffold_controller_generator.rb +27 -0
  231. data/lib/generators/rails/scaffold_controller/templates/controller.rb +85 -0
  232. data/lib/generators/rails/session_migration/USAGE +8 -0
  233. data/lib/generators/rails/session_migration/session_migration_generator.rb +8 -0
  234. data/lib/generators/rails/stylesheets/USAGE +5 -0
  235. data/lib/generators/rails/stylesheets/stylesheets_generator.rb +9 -0
  236. data/lib/generators/rails/stylesheets/templates/scaffold.css +61 -0
  237. data/lib/generators/test_unit.rb +8 -0
  238. data/lib/generators/test_unit/controller/controller_generator.rb +14 -0
  239. data/lib/generators/test_unit/controller/templates/functional_test.rb +8 -0
  240. data/lib/generators/test_unit/helper/helper_generator.rb +13 -0
  241. data/lib/generators/test_unit/helper/templates/helper_test.rb +4 -0
  242. data/lib/generators/test_unit/integration/integration_generator.rb +13 -0
  243. data/lib/generators/test_unit/integration/templates/integration_test.rb +10 -0
  244. data/lib/generators/test_unit/mailer/mailer_generator.rb +21 -0
  245. data/lib/generators/test_unit/mailer/templates/fixture +3 -0
  246. data/lib/generators/test_unit/mailer/templates/functional_test.rb +22 -0
  247. data/lib/generators/test_unit/model/model_generator.rb +24 -0
  248. data/lib/generators/test_unit/model/templates/fixtures.yml +23 -0
  249. data/lib/generators/test_unit/model/templates/unit_test.rb +8 -0
  250. data/lib/generators/test_unit/observer/observer_generator.rb +13 -0
  251. data/lib/generators/test_unit/observer/templates/unit_test.rb +8 -0
  252. data/lib/generators/test_unit/performance/performance_generator.rb +13 -0
  253. data/lib/generators/test_unit/performance/templates/performance_test.rb +9 -0
  254. data/lib/generators/test_unit/plugin/plugin_generator.rb +13 -0
  255. data/lib/generators/test_unit/plugin/templates/%file_name%_test.rb.tt +8 -0
  256. data/lib/generators/test_unit/plugin/templates/test_helper.rb +3 -0
  257. data/lib/generators/test_unit/scaffold/scaffold_generator.rb +18 -0
  258. data/lib/generators/test_unit/scaffold/templates/functional_test.rb +47 -0
  259. data/lib/rails.rb +95 -0
  260. data/lib/rails/all.rb +14 -0
  261. data/lib/rails/application.rb +125 -0
  262. data/lib/rails/application/bootstrap.rb +85 -0
  263. data/lib/rails/application/configurable.rb +19 -0
  264. data/lib/rails/application/configuration.rb +86 -0
  265. data/lib/rails/application/finisher.rb +49 -0
  266. data/lib/rails/application/metal_loader.rb +50 -0
  267. data/lib/rails/application/railties.rb +31 -0
  268. data/lib/rails/application/routes_reloader.rb +46 -0
  269. data/lib/rails/backtrace_cleaner.rb +54 -0
  270. data/lib/rails/code_statistics.rb +107 -0
  271. data/lib/rails/commands.rb +72 -0
  272. data/lib/rails/commands/application.rb +13 -0
  273. data/lib/rails/commands/console.rb +55 -0
  274. data/lib/rails/commands/dbconsole.rb +104 -0
  275. data/lib/rails/commands/destroy.rb +9 -0
  276. data/lib/rails/commands/generate.rb +9 -0
  277. data/lib/rails/commands/performance/benchmarker.rb +23 -0
  278. data/lib/rails/commands/performance/profiler.rb +46 -0
  279. data/lib/rails/commands/plugin.rb +542 -0
  280. data/lib/rails/commands/runner.rb +51 -0
  281. data/lib/rails/commands/server.rb +75 -0
  282. data/lib/rails/commands/update.rb +9 -0
  283. data/lib/rails/configuration.rb +191 -0
  284. data/lib/rails/console/app.rb +33 -0
  285. data/lib/rails/console/helpers.rb +5 -0
  286. data/lib/rails/console/sandbox.rb +6 -0
  287. data/lib/rails/deprecation.rb +62 -0
  288. data/lib/rails/dispatcher.rb +24 -0
  289. data/lib/rails/engine.rb +130 -0
  290. data/lib/rails/engine/configurable.rb +25 -0
  291. data/lib/rails/engine/configuration.rb +49 -0
  292. data/lib/rails/generators.rb +289 -0
  293. data/lib/rails/generators/actions.rb +309 -0
  294. data/lib/rails/generators/active_model.rb +78 -0
  295. data/lib/rails/generators/base.rb +362 -0
  296. data/lib/rails/generators/generated_attribute.rb +48 -0
  297. data/lib/rails/generators/migration.rb +64 -0
  298. data/lib/rails/generators/named_base.rb +95 -0
  299. data/lib/rails/generators/resource_helpers.rb +80 -0
  300. data/lib/rails/generators/test_case.rb +239 -0
  301. data/lib/rails/initializable.rb +97 -0
  302. data/lib/rails/paths.rb +144 -0
  303. data/lib/rails/performance_test_help.rb +3 -0
  304. data/lib/rails/plugin.rb +64 -0
  305. data/lib/rails/rack.rb +8 -0
  306. data/lib/rails/rack/debugger.rb +23 -0
  307. data/lib/rails/rack/log_tailer.rb +33 -0
  308. data/lib/rails/rack/logger.rb +34 -0
  309. data/lib/rails/rack/static.rb +5 -0
  310. data/lib/rails/railtie.rb +74 -0
  311. data/lib/rails/railtie/configurable.rb +23 -0
  312. data/lib/rails/railtie/configuration.rb +9 -0
  313. data/lib/rails/railties_path.rb +1 -0
  314. data/lib/rails/ruby_version_check.rb +10 -0
  315. data/lib/rails/rubyprof_ext.rb +35 -0
  316. data/lib/rails/source_annotation_extractor.rb +102 -0
  317. data/lib/rails/subscriber.rb +108 -0
  318. data/lib/rails/subscriber/test_helper.rb +98 -0
  319. data/lib/rails/tasks.rb +16 -0
  320. data/lib/rails/tasks/annotations.rake +20 -0
  321. data/lib/rails/tasks/documentation.rake +96 -0
  322. data/lib/rails/tasks/framework.rake +69 -0
  323. data/lib/rails/tasks/log.rake +9 -0
  324. data/lib/rails/tasks/middleware.rake +7 -0
  325. data/lib/rails/tasks/misc.rake +71 -0
  326. data/lib/rails/tasks/routes.rake +17 -0
  327. data/lib/rails/tasks/statistics.rake +16 -0
  328. data/lib/rails/tasks/tmp.rake +37 -0
  329. data/lib/rails/test_help.rb +30 -0
  330. data/lib/rails/test_unit/railtie.rb +17 -0
  331. data/lib/rails/test_unit/testing.rake +130 -0
  332. data/lib/rails/version.rb +9 -0
  333. data/lib/rails/webrick_server.rb +156 -0
  334. metadata +427 -0
@@ -0,0 +1,204 @@
1
+ h2. Active Record Basics
2
+
3
+ This guide is an introduction to Active Record. After reading this guide we hope that you'll learn:
4
+
5
+ * What Object Relational Mapping and Active Record are and how they are used in Rails
6
+ * How Active Record fits into the Model-View-Controller paradigm
7
+ * How to use Active Record models to manipulate data stored in a relational database
8
+ * Active Record schema naming conventions
9
+ * The concepts of database migrations, validations and callbacks
10
+
11
+ endprologue.
12
+
13
+ h3. What is Active Record?
14
+
15
+ Active Record is the M in "MVC":getting_started.html#the-mvc-architecture - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.
16
+
17
+ h4. The Active Record Pattern
18
+
19
+ Active Record was described by Martin Fowler in his book _Patterns of Enterprise Application Architecture_. In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring data access logic is part of the object will educate users of that object on how to write to and read from the database.
20
+
21
+ h4. Object Relational Mapping
22
+
23
+ Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.
24
+
25
+ h4. Active Record as an ORM Framework
26
+
27
+ Active Record gives us several mechanisms, the most important being the ability to:
28
+
29
+ * Represent models and their data
30
+ * Represent associations between these models
31
+ * Represent inheritance hierarchies through related models
32
+ * Validate models before they get persisted to the database
33
+ * Perform database operations in an object-oriented fashion.
34
+
35
+ h3. Convention over Configuration in ActiveRecord
36
+
37
+ When writing applications using other programming languages or frameworks, it may be necessary to write a lot of configuration code. This is particularly true for ORM frameworks in general. However, if you follow the conventions adopted by Rails, you'll need to write very little configuration (in some case no configuration at all) when creating ActiveRecord models. The idea is that if you configure your applications in the very same way most of the times then this should be the default way. In this cases, explicit configuration would be needed only in those cases where you can't follow the conventions for any reason.
38
+
39
+ h4. Naming Conventions
40
+
41
+ By default, ActiveRecord uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class +Book+, you should have a database table called *books*. The Rails pluralization mechanisms are very powerful, being capable to pluralize (and singularize) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the camelCase form, while the table name must contain the words separated by underscores. Examples:
42
+
43
+ * Database Table - Plural with underscores separating words i.e. (book_clubs)
44
+ * Model Class - Singular with the first letter of each word capitalized i.e. (BookClub)
45
+
46
+ |_.Model / Class |_.Table / Schema |
47
+ |Post |posts|
48
+ |LineItem |line_items|
49
+ |Deer |deer|
50
+ |Mouse |mice|
51
+ |Person |people|
52
+
53
+
54
+ h4. Schema Conventions
55
+
56
+ ActiveRecord uses naming conventions for the columns in database tables, depending on the purpose of these columns.
57
+
58
+ * *Foreign keys* - These fields should be named following the pattern table_id i.e. (item_id, order_id). These are the fields that ActiveRecord will look for when you create associations between your models.
59
+ * *Primary keys* - By default, ActiveRecord will use an integer column named "id" as the table's primary key. When using "Rails Migrations":migrations.html to create your tables, this column will be automatically created.
60
+
61
+ There are also some optional column names that will create additional features to ActiveRecord instances:
62
+
63
+ * *created_at / created_on* - ActiveRecord will store the current date and time to this field when creating the record.
64
+ * *updated_at / updated_on* - ActiveRecord will store the current date and times to this field when updating the record.
65
+ * *lock_version* - Adds "optimistic locking":http://api.rubyonrails.com/classes/ActiveRecord/Locking.html to a model.
66
+ * *type* - Specifies that the model uses "Single Table Inheritance":http://api.rubyonrails.com/classes/ActiveRecord/Base.html
67
+ * *(table_name)_count* - Used to cache the number of belonging objects on associations. For example, a +comments_count+ column in a +Post+ class that has many instances of +Comment+ will cache the number of existent comments for each post.
68
+
69
+ NOTE: While these column names are optional they are in fact reserved by ActiveRecord. Steer clear of reserved keywords unless you want the extra functionality. For example, "type" is a reserved keyword used to designate a table using Single Table Inheritance. If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling.
70
+
71
+ h3. Creating ActiveRecord Models
72
+
73
+ It's very easy to create ActiveRecord models. All you have to do is to subclass the ActiveRecord::Base class and you're good to go:
74
+
75
+ <ruby>
76
+ class Product < ActiveRecord::Base; end
77
+ </ruby>
78
+
79
+ This will create a +Product+ model, mapped to a *products* table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. So, suppose that the *products* table was created using a SQL sentence like:
80
+
81
+ <sql>
82
+ CREATE TABLE products (
83
+ id int(11) NOT NULL auto_increment,
84
+ name varchar(255),
85
+ PRIMARY KEY (id)
86
+ );
87
+ </sql>
88
+
89
+ Following the table schema above, you would be able to write code like the following:
90
+
91
+ <ruby>
92
+ p = Product.new
93
+ p.name = "Some Book"
94
+ puts p.name # "Some Book"
95
+ </ruby>
96
+
97
+ h3. Overriding the Naming Conventions
98
+
99
+ What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.
100
+
101
+ You can use the +ActiveRecord::Base.set_table_name+ method to specify the table name that should be used:
102
+ <ruby>
103
+ class Product < ActiveRecord::Base
104
+ set_table_name "PRODUCT"
105
+ end
106
+ </ruby>
107
+
108
+ It's also possible to override the column that should be used as the table's primary key. Use the +ActiveRecord::Base.set_primary_key+ method for that:
109
+ <ruby>
110
+ class Product < ActiveRecord::Base
111
+ set_primary_key "product_id"
112
+ end
113
+ </ruby>
114
+
115
+ h3. Reading and Writing Data
116
+
117
+ CRUD is an acronym for the four verbs we use to operate on data: Create, Read, Update, Delete. Active Record automatically creates methods to allow an application to read and manipulate data stored within its tables.
118
+
119
+ h4. Create
120
+
121
+ Active Record objects can be created from a hash, a block or have its attributes manually set after creation. The _new_ method will return a new object while _create_ will return the object and save it to the database.
122
+
123
+ For example, given a model +User+ with attributes of +name+ and +occupation+, the _create_ method call will create and save a new record into the database:
124
+
125
+ <ruby>
126
+ user = User.create(:name => "David", :occupation => "Code Artist")
127
+ </ruby>
128
+
129
+ Using the _new_ method, an object can be created without being saved:
130
+
131
+ <ruby>
132
+ user = User.new
133
+ user.name = "David"
134
+ user.occupation = "Code Artist"
135
+ </ruby>
136
+
137
+ A call to _user.save_ will commit the record to the database.
138
+
139
+ Finally, passing a block to either create or new will return a new User object:
140
+
141
+ <ruby>
142
+ user = User.new do |u|
143
+ u.name = "David"
144
+ u.occupation = "Code Artist"
145
+ end
146
+ </ruby>
147
+
148
+ h4. Read
149
+
150
+ ActiveRecord provides a rich API for accessing data within a database. Below are a few examples of different data access methods provided by ActiveRecord.
151
+
152
+ <ruby>
153
+ # return all records
154
+ users = User.all
155
+ </ruby>
156
+
157
+ <ruby>
158
+ # return first record
159
+ user = User.first
160
+ </ruby>
161
+
162
+ <ruby>
163
+ # return the first user named David
164
+ david = User.find_by_name('David')
165
+ </ruby>
166
+
167
+ <ruby>
168
+ # find all users named David who are Code Artists and sort by created_at in reverse chronological order
169
+ users = User.all(:conditions => { :name => 'David', :occupation => 'Code Artist'}, :order => 'created_at DESC')
170
+ </ruby>
171
+
172
+ You can learn more about querying an Active Record model in the "Active Record Query Interface":"active_record_querying.html" guide.
173
+
174
+ h4. Update
175
+
176
+ Once an Active Record object has been retrieved, its attributes can be modified and it can be saved to the database.
177
+
178
+ <ruby>
179
+ user = User.find_by_name('David')
180
+ user.name = 'Dave'
181
+ user.save
182
+ </ruby>
183
+
184
+ h4. Delete
185
+
186
+ Likewise, once retrieved an Active Record object can be destroyed which removes it from the database.
187
+
188
+ <ruby>
189
+ user = User.find_by_name('David')
190
+ user.destroy
191
+ </ruby>
192
+
193
+
194
+ h3. Validations
195
+
196
+ Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format and many more. You can learn more about validations in the "Active Record Validations and Callbacks guide":activerecord_validations_callbacks.html#validations-overview.
197
+
198
+ h3. Callbacks
199
+
200
+ Active Record callbacks allow you to attach code to certain events in the life-cycle of your models. This enables you to add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on. You can learn more about callbacks in the "Active Record Validations and Callbacks guide":activerecord_validations_callbacks.html#callbacks-overview.
201
+
202
+ h3. Migrations
203
+
204
+ Rails provides a domain-specific language for managing a database schema called migrations. Migrations are stored in files which are executed against any database that Active Record support using rake. Rails keeps track of which files have been committed to the database and provides rollback features. You can learn more about migrations in the "Active Record Migrations guide":migrations.html
@@ -0,0 +1,961 @@
1
+ h2. Active Record Query Interface
2
+
3
+ This guide covers different ways to retrieve data from the database using Active Record. By referring to this guide, you will be able to:
4
+
5
+ * Find records using a variety of methods and conditions
6
+ * Specify the order, retrieved attributes, grouping, and other properties of the found records
7
+ * Use eager loading to reduce the number of database queries needed for data retrieval
8
+ * Use dynamic finders methods
9
+ * Check for the existence of particular records
10
+ * Perform various calculations on Active Record models
11
+
12
+ endprologue.
13
+
14
+ If you're used to using raw SQL to find database records then, generally, you will find that there are better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
15
+
16
+ Code examples throughout this guide will refer to one or more of the following models:
17
+
18
+ TIP: All of the following models uses +id+ as the primary key, unless specified otherwise.
19
+
20
+ <br />
21
+
22
+ <ruby>
23
+ class Client < ActiveRecord::Base
24
+ has_one :address
25
+ has_many :orders
26
+ has_and_belongs_to_many :roles
27
+ end
28
+ </ruby>
29
+
30
+ <ruby>
31
+ class Address < ActiveRecord::Base
32
+ belongs_to :client
33
+ end
34
+ </ruby>
35
+
36
+ <ruby>
37
+ class Order < ActiveRecord::Base
38
+ belongs_to :client, :counter_cache => true
39
+ end
40
+ </ruby>
41
+
42
+ <ruby>
43
+ class Role < ActiveRecord::Base
44
+ has_and_belongs_to_many :clients
45
+ end
46
+ </ruby>
47
+
48
+ Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same.
49
+
50
+ h3. Retrieving Objects from the Database
51
+
52
+ To retrieve objects from the database, Active Record provides a class method called +Model.find+. This method allows you to pass arguments into it to perform certain queries on your database without the need of writing raw SQL.
53
+
54
+ Primary operation of <tt>Model.find(options)</tt> can be summarized as:
55
+
56
+ * Convert the supplied options to an equivalent SQL query.
57
+ * Fire the SQL query and retrieve the corresponding results from the database.
58
+ * Instantiate the equivalent Ruby object of the appropriate model for every resulting row.
59
+ * Run +after_find+ callbacks if any.
60
+
61
+ h4. Retrieving a Single Object
62
+
63
+ Active Record lets you retrieve a single object using three different ways.
64
+
65
+ h5. Using a Primary Key
66
+
67
+ Using <tt>Model.find(primary_key, options = nil)</tt>, you can retrieve the object corresponding to the supplied _primary key_ and matching the supplied options (if any). For example:
68
+
69
+ <ruby>
70
+ # Find the client with primary key (id) 10.
71
+ client = Client.find(10)
72
+ => #<Client id: 10, name: => "Ryan">
73
+ </ruby>
74
+
75
+ SQL equivalent of the above is:
76
+
77
+ <sql>
78
+ SELECT * FROM clients WHERE (clients.id = 10)
79
+ </sql>
80
+
81
+ <tt>Model.find(primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception if no matching record is found.
82
+
83
+ h5. +first+
84
+
85
+ <tt>Model.first(options = nil)</tt> finds the first record matched by the supplied options. If no +options+ are supplied, the first matching record is returned. For example:
86
+
87
+ <ruby>
88
+ client = Client.first
89
+ => #<Client id: 1, name: => "Lifo">
90
+ </ruby>
91
+
92
+ SQL equivalent of the above is:
93
+
94
+ <sql>
95
+ SELECT * FROM clients LIMIT 1
96
+ </sql>
97
+
98
+ <tt>Model.first</tt> returns +nil+ if no matching record is found. No exception will be raised.
99
+
100
+ NOTE: +Model.find(:first, options)+ is equivalent to +Model.first(options)+
101
+
102
+ h5. +last+
103
+
104
+ <tt>Model.last(options = nil)</tt> finds the last record matched by the supplied options. If no +options+ are supplied, the last matching record is returned. For example:
105
+
106
+ <ruby>
107
+ client = Client.last
108
+ => #<Client id: 221, name: => "Russel">
109
+ </ruby>
110
+
111
+ SQL equivalent of the above is:
112
+
113
+ <sql>
114
+ SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
115
+ </sql>
116
+
117
+ <tt>Model.last</tt> returns +nil+ if no matching record is found. No exception will be raised.
118
+
119
+ NOTE: +Model.find(:last, options)+ is equivalent to +Model.last(options)+
120
+
121
+ h4. Retrieving Multiple Objects
122
+
123
+ h5. Using Multiple Primary Keys
124
+
125
+ <tt>Model.find(array_of_primary_key, options = nil)</tt> also accepts an array of _primary keys_. An array of all the matching records for the supplied _primary keys_ is returned. For example:
126
+
127
+ <ruby>
128
+ # Find the clients with primary keys 1 and 10.
129
+ client = Client.find(1, 10) # Or even Client.find([1, 10])
130
+ => [#<Client id: 1, name: => "Lifo">, #<Client id: 10, name: => "Ryan">]
131
+ </ruby>
132
+
133
+ SQL equivalent of the above is:
134
+
135
+ <sql>
136
+ SELECT * FROM clients WHERE (clients.id IN (1,10))
137
+ </sql>
138
+
139
+ <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
140
+
141
+ h5. Find all
142
+
143
+ <tt>Model.all(options = nil)</tt> finds all the records matching the supplied +options+. If no +options+ are supplied, all rows from the database are returned.
144
+
145
+ <ruby>
146
+ # Find all the clients.
147
+ clients = Client.all
148
+ => [#<Client id: 1, name: => "Lifo">, #<Client id: 10, name: => "Ryan">, #<Client id: 221, name: => "Russel">]
149
+ </ruby>
150
+
151
+ And the equivalent SQL is:
152
+
153
+ <sql>
154
+ SELECT * FROM clients
155
+ </sql>
156
+
157
+ <tt>Model.all</tt> returns an empty array +[]+ if no matching record is found. No exception will be raised.
158
+
159
+ NOTE: +Model.find(:all, options)+ is equivalent to +Model.all(options)+
160
+
161
+ h4. Retrieving Multiple Objects in Batches
162
+
163
+ Sometimes you need to iterate over a large set of records. For example to send a newsletter to all users, to export some data, etc.
164
+
165
+ The following may seem very straight forward at first:
166
+
167
+ <ruby>
168
+ # Very inefficient when users table has thousands of rows.
169
+ User.all.each do |user|
170
+ NewsLetter.weekly_deliver(user)
171
+ end
172
+ </ruby>
173
+
174
+ But if the total number of rows in the table is very large, the above approach may vary from being under performant to just plain impossible.
175
+
176
+ This is because +User.all+ makes Active Record fetch _the entire table_, build a model object per row, and keep the entire array in the memory. Sometimes that is just too many objects and demands too much memory.
177
+
178
+ h5. +find_each+
179
+
180
+ To efficiently iterate over a large table, Active Record provides a batch finder method called +find_each+:
181
+
182
+ <ruby>
183
+ User.find_each do |user|
184
+ NewsLetter.weekly_deliver(user)
185
+ end
186
+ </ruby>
187
+
188
+ *Configuring the batch size*
189
+
190
+ Behind the scenes +find_each+ fetches rows in batches of +1000+ and yields them one by one. The size of the underlying batches is configurable via the +:batch_size+ option.
191
+
192
+ To fetch +User+ records in batch size of +5000+:
193
+
194
+ <ruby>
195
+ User.find_each(:batch_size => 5000) do |user|
196
+ NewsLetter.weekly_deliver(user)
197
+ end
198
+ </ruby>
199
+
200
+ *Starting batch find from a specific primary key*
201
+
202
+ Records are fetched in ascending order on the primary key, which must be an integer. The +:start+ option allows you to configure the first ID of the sequence if the lowest is not the one you need. This may be useful for example to be able to resume an interrupted batch process if it saves the last processed ID as a checkpoint.
203
+
204
+ To send newsletters only to users with the primary key starting from +2000+:
205
+
206
+ <ruby>
207
+ User.find_each(:batch_size => 5000, :start => 2000) do |user|
208
+ NewsLetter.weekly_deliver(user)
209
+ end
210
+ </ruby>
211
+
212
+ *Additional options*
213
+
214
+ +find_each+ accepts the same options as the regular +find+ method. However, +:order+ and +:limit+ are needed internally and hence not allowed to be passed explicitly.
215
+
216
+ h5. +find_in_batches+
217
+
218
+ You can also work by chunks instead of row by row using +find_in_batches+. This method is analogous to +find_each+, but it yields arrays of models instead:
219
+
220
+ <ruby>
221
+ # Works in chunks of 1000 invoices at a time.
222
+ Invoice.find_in_batches(:include => :invoice_lines) do |invoices|
223
+ export.add_invoices(invoices)
224
+ end
225
+ </ruby>
226
+
227
+ The above will yield the supplied block with +1000+ invoices every time.
228
+
229
+ h3. Conditions
230
+
231
+ The +find+ method allows you to specify conditions to limit the records returned, representing the +WHERE+-part of the SQL statement. Conditions can either be specified as a string, array, or hash.
232
+
233
+ h4. Pure String Conditions
234
+
235
+ If you'd like to add conditions to your find, you could just specify them in there, just like +Client.first(:conditions => "orders_count = '2'")+. This will find all clients where the +orders_count+ field's value is 2.
236
+
237
+ WARNING: Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, +Client.first(:conditions => "name LIKE '%#{params[:name]}%'")+ is not safe. See the next section for the preferred way to handle conditions using an array.
238
+
239
+ h4. Array Conditions
240
+
241
+ Now what if that number could vary, say as an argument from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like:
242
+
243
+ <ruby>
244
+ Client.first(:conditions => ["orders_count = ?", params[:orders]])
245
+ </ruby>
246
+
247
+ Active Record will go through the first element in the conditions value and any additional elements will replace the question marks +(?)+ in the first element.
248
+
249
+ Or if you want to specify two conditions, you can do it like:
250
+
251
+ <ruby>
252
+ Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])
253
+ </ruby>
254
+
255
+ In this example, the first question mark will be replaced with the value in +params[:orders]+ and the second will be replaced with the SQL representation of +false+, which depends on the adapter.
256
+
257
+ The reason for doing code like:
258
+
259
+ <ruby>
260
+ Client.first(:conditions => ["orders_count = ?", params[:orders]])
261
+ </ruby>
262
+
263
+ instead of:
264
+
265
+ <ruby>
266
+ Client.first(:conditions => "orders_count = #{params[:orders]}")
267
+ </ruby>
268
+
269
+ is because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string.
270
+
271
+ TIP: For more information on the dangers of SQL injection, see the "Ruby on Rails Security Guide":security.html#sql-injection.
272
+
273
+ h5. Placeholder Conditions
274
+
275
+ Similar to the +(?)+ replacement style of params, you can also specify keys/values hash in your array conditions:
276
+
277
+ <ruby>
278
+ Client.all(:conditions =>
279
+ ["created_at >= :start_date AND created_at <= :end_date", { :start_date => params[:start_date], :end_date => params[:end_date] }])
280
+ </ruby>
281
+
282
+ This makes for clearer readability if you have a large number of variable conditions.
283
+
284
+ h5. Range Conditions
285
+
286
+ If you're looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the +IN+ SQL statement for this. If you had two dates coming in from a controller you could do something like this to look for a range:
287
+
288
+ <ruby>
289
+ Client.all(:conditions => ["created_at IN (?)",
290
+ (params[:start_date].to_date)..(params[:end_date].to_date)])
291
+ </ruby>
292
+
293
+ This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against.
294
+
295
+ <sql>
296
+ SELECT * FROM users WHERE (created_at IN
297
+ ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05',
298
+ '2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11',
299
+ '2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17',
300
+ '2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',...
301
+ ‘2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20',
302
+ '2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26',
303
+ '2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
304
+ </sql>
305
+
306
+ h5. Time and Date Conditions
307
+
308
+ Things can get *really* messy if you pass in Time objects as it will attempt to compare your field to *every second* in that range:
309
+
310
+ <ruby>
311
+ Client.all(:conditions => ["created_at IN (?)",
312
+ (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)])
313
+ </ruby>
314
+
315
+ <sql>
316
+ SELECT * FROM users WHERE (created_at IN
317
+ ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ...
318
+ '2007-12-01 23:59:59', '2007-12-02 00:00:00'))
319
+ </sql>
320
+
321
+ This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:
322
+
323
+ <shell>
324
+ Got a packet bigger than 'max_allowed_packet' bytes: _query_
325
+ </shell>
326
+
327
+ Where _query_ is the actual query used to get that error.
328
+
329
+ In this example it would be better to use greater-than and less-than operators in SQL, like so:
330
+
331
+ <ruby>
332
+ Client.all(:conditions =>
333
+ ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]])
334
+ </ruby>
335
+
336
+ You can also use the greater-than-or-equal-to and less-than-or-equal-to like this:
337
+
338
+ <ruby>
339
+ Client.all(:conditions =>
340
+ ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
341
+ </ruby>
342
+
343
+ Just like in Ruby. If you want a shorter syntax be sure to check out the "Hash Conditions":#hash-conditions section later on in the guide.
344
+
345
+ h4. Hash Conditions
346
+
347
+ Active Record also allows you to pass in a hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want conditionalised and the values of how you want to conditionalise them:
348
+
349
+ NOTE: Only equality, range and subset checking are possible with Hash conditions.
350
+
351
+ h5. Equality Conditions
352
+
353
+ <ruby>
354
+ Client.all(:conditions => { :locked => true })
355
+ </ruby>
356
+
357
+ The field name does not have to be a symbol it can also be a string:
358
+
359
+ <ruby>
360
+ Client.all(:conditions => { 'locked' => true })
361
+ </ruby>
362
+
363
+ h5. Range Conditions
364
+
365
+ The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section.
366
+
367
+ <ruby>
368
+ Client.all(:conditions => { :created_at => (Time.now.midnight - 1.day)..Time.now.midnight})
369
+ </ruby>
370
+
371
+ This will find all clients created yesterday by using a +BETWEEN+ SQL statement:
372
+
373
+ <sql>
374
+ SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
375
+ </sql>
376
+
377
+ This demonstrates a shorter syntax for the examples in "Array Conditions":#array-conditions
378
+
379
+ h5. Subset Conditions
380
+
381
+ If you want to find records using the +IN+ expression you can pass an array to the conditions hash:
382
+
383
+ <ruby>
384
+ Client.all(:conditions => { :orders_count => [1,3,5] })
385
+ </ruby>
386
+
387
+ This code will generate SQL like this:
388
+
389
+ <sql>
390
+ SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
391
+ </sql>
392
+
393
+ h3. Find Options
394
+
395
+ Apart from +:conditions+, +Model.find+ takes a variety of other options via the options hash for customizing the resulting record set.
396
+
397
+ <ruby>
398
+ Model.find(id_or_array_of_ids, options_hash)
399
+ Model.find(:last, options_hash)
400
+ Model.find(:first, options_hash)
401
+
402
+ Model.first(options_hash)
403
+ Model.last(options_hash)
404
+ Model.all(options_hash)
405
+ </ruby>
406
+
407
+ The following sections give a top level overview of all the possible keys for the +options_hash+.
408
+
409
+ h4. Ordering
410
+
411
+ To retrieve records from the database in a specific order, you can specify the +:order+ option to the +find+ call.
412
+
413
+ For example, if you're getting a set of records and want to order them in ascending order by the +created_at+ field in your table:
414
+
415
+ <ruby>
416
+ Client.all(:order => "created_at")
417
+ </ruby>
418
+
419
+ You could specify +ASC+ or +DESC+ as well:
420
+
421
+ <ruby>
422
+ Client.all(:order => "created_at DESC")
423
+ # OR
424
+ Client.all(:order => "created_at ASC")
425
+ </ruby>
426
+
427
+ Or ordering by multiple fields:
428
+
429
+ <ruby>
430
+ Client.all(:order => "orders_count ASC, created_at DESC")
431
+ </ruby>
432
+
433
+ h4. Selecting Specific Fields
434
+
435
+ By default, <tt>Model.find</tt> selects all the fields from the result set using +select *+.
436
+
437
+ To select only a subset of fields from the result set, you can specify the subset via +:select+ option on the +find+.
438
+
439
+ NOTE: If the +:select+ option is used, all the returning objects will be "read only":#readonly-objects.
440
+
441
+ <br />
442
+
443
+ For example, to select only +viewable_by+ and +locked+ columns:
444
+
445
+ <ruby>
446
+ Client.all(:select => "viewable_by, locked")
447
+ </ruby>
448
+
449
+ The SQL query used by this find call will be somewhat like:
450
+
451
+ <sql>
452
+ SELECT viewable_by, locked FROM clients
453
+ </sql>
454
+
455
+ Be careful because this also means you're initializing a model object with only the fields that you've selected. If you attempt to access a field that is not in the initialized record you'll receive:
456
+
457
+ <shell>
458
+ ActiveRecord::MissingAttributeError: missing attribute: <attribute>
459
+ </shell>
460
+
461
+ Where +&lt;attribute&gt;+ is the attribute you asked for. The +id+ method will not raise the +ActiveRecord::MissingAttributeError+, so just be careful when working with associations because they need the +id+ method to function properly.
462
+
463
+ You can also call SQL functions within the select option. For example, if you would like to only grab a single record per unique value in a certain field by using the +DISTINCT+ function you can do it like this:
464
+
465
+ <ruby>
466
+ Client.all(:select => "DISTINCT(name)")
467
+ </ruby>
468
+
469
+ h4. Limit and Offset
470
+
471
+ To apply +LIMIT+ to the SQL fired by the +Model.find+, you can specify the +LIMIT+ using +:limit+ and +:offset+ options on the find.
472
+
473
+ If you want to limit the amount of records to a certain subset of all the records retrieved you usually use +:limit+ for this, sometimes coupled with +:offset+. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. For example:
474
+
475
+ <ruby>
476
+ Client.all(:limit => 5)
477
+ </ruby>
478
+
479
+ This code will return a maximum of 5 clients and because it specifies no offset it will return the first 5 clients in the table. The SQL it executes will look like this:
480
+
481
+ <sql>
482
+ SELECT * FROM clients LIMIT 5
483
+ </sql>
484
+
485
+ Or specifying both +:limit+ and +:offset+:
486
+
487
+ <ruby>
488
+ Client.all(:limit => 5, :offset => 5)
489
+ </ruby>
490
+
491
+ This code will return a maximum of 5 clients and because it specifies an offset this time, it will return these records starting from the 5th client in the clients table. The SQL looks like:
492
+
493
+ <sql>
494
+ SELECT * FROM clients LIMIT 5, 5
495
+ </sql>
496
+
497
+ h4. Group
498
+
499
+ To apply +GROUP BY+ clause to the SQL fired by the +Model.find+, you can specify the +:group+ option on the find.
500
+
501
+ For example, if you want to find a collection of the dates orders were created on:
502
+
503
+ <ruby>
504
+ Order.all(:group => "date(created_at)", :order => "created_at")
505
+ </ruby>
506
+
507
+ And this will give you a single +Order+ object for each date where there are orders in the database.
508
+
509
+ The SQL that would be executed would be something like this:
510
+
511
+ <sql>
512
+ SELECT * FROM orders GROUP BY date(created_at)
513
+ </sql>
514
+
515
+ h4. Having
516
+
517
+ SQL uses +HAVING+ clause to specify conditions on the +GROUP BY+ fields. You can specify the +HAVING+ clause to the SQL fired by the +Model.find+ using +:having+ option on the find.
518
+
519
+ For example:
520
+
521
+ <ruby>
522
+ Order.all(:group => "date(created_at)", :having => ["created_at > ?", 1.month.ago])
523
+ </ruby>
524
+
525
+ The SQL that would be executed would be something like this:
526
+
527
+ <sql>
528
+ SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15'
529
+ </sql>
530
+
531
+ This will return single order objects for each day, but only for the last month.
532
+
533
+ h4. Readonly Objects
534
+
535
+ To explicitly disallow modification/destruction of the matching records returned by +Model.find+, you could specify the +:readonly+ option as +true+ to the find call.
536
+
537
+ Any attempt to alter or destroy the readonly records will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception. To set this option, specify it like this:
538
+
539
+ <ruby>
540
+ Client.first(:readonly => true)
541
+ </ruby>
542
+
543
+ If you assign this record to a variable client, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception:
544
+
545
+ <ruby>
546
+ client = Client.first(:readonly => true)
547
+ client.locked = false
548
+ client.save
549
+ </ruby>
550
+
551
+ h4. Locking Records for Update
552
+
553
+ Locking is helpful for preventing the race conditions when updating records in the database and ensuring atomic updated. Active Record provides two locking mechanism:
554
+
555
+ * Optimistic Locking
556
+ * Pessimistic Locking
557
+
558
+ h5. Optimistic Locking
559
+
560
+ Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An +ActiveRecord::StaleObjectError+ exception is thrown if that has occurred and the update is ignored.
561
+
562
+ <strong>Optimistic locking column</strong>
563
+
564
+ In order to use optimistic locking, the table needs to have a column called +lock_version+. Each time the record is updated, Active Record increments the +lock_version+ column and the locking facilities ensure that records instantiated twice will let the last one saved raise an +ActiveRecord::StaleObjectError+ exception if the first was also updated. Example:
565
+
566
+ <ruby>
567
+ c1 = Client.find(1)
568
+ c2 = Client.find(1)
569
+
570
+ c1.name = "Michael"
571
+ c1.save
572
+
573
+ c2.name = "should fail"
574
+ c2.save # Raises a ActiveRecord::StaleObjectError
575
+ </ruby>
576
+
577
+ You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, or otherwise apply the business logic needed to resolve the conflict.
578
+
579
+ NOTE: You must ensure that your database schema defaults the +lock_version+ column to +0+.
580
+
581
+ <br />
582
+
583
+ This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
584
+
585
+ To override the name of the +lock_version+ column, +ActiveRecord::Base+ provides a class method called +set_locking_column+:
586
+
587
+ <ruby>
588
+ class Client < ActiveRecord::Base
589
+ set_locking_column :lock_client_column
590
+ end
591
+ </ruby>
592
+
593
+ h5. Pessimistic Locking
594
+
595
+ Pessimistic locking uses locking mechanism provided by the underlying database. Passing +:lock => true+ to +Model.find+ obtains an exclusive lock on the selected rows. +Model.find+ using +:lock+ are usually wrapped inside a transaction for preventing deadlock conditions.
596
+
597
+ For example:
598
+
599
+ <ruby>
600
+ Item.transaction do
601
+ i = Item.first(:lock => true)
602
+ i.name = 'Jones'
603
+ i.save
604
+ end
605
+ </ruby>
606
+
607
+ The above session produces the following SQL for a MySQL backend:
608
+
609
+ <sql>
610
+ SQL (0.2ms) BEGIN
611
+ Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE
612
+ Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1
613
+ SQL (0.8ms) COMMIT
614
+ </sql>
615
+
616
+ You can also pass raw SQL to the +:lock+ option to allow different types of locks. For example, MySQL has an expression called +LOCK IN SHARE MODE+ where you can lock a record but still allow other queries to read it. To specify this expression just pass it in as the lock option:
617
+
618
+ <ruby>
619
+ Item.transaction do
620
+ i = Item.find(1, :lock => "LOCK IN SHARE MODE")
621
+ i.increment!(:views)
622
+ end
623
+ </ruby>
624
+
625
+ h3. Joining Tables
626
+
627
+ <tt>Model.find</tt> provides a +:joins+ option for specifying +JOIN+ clauses on the resulting SQL. There multiple different ways to specify the +:joins+ option:
628
+
629
+ h4. Using a String SQL Fragment
630
+
631
+ You can just supply the raw SQL specifying the +JOIN+ clause to the +:joins+ option. For example:
632
+
633
+ <ruby>
634
+ Client.all(:joins => 'LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
635
+ </ruby>
636
+
637
+ This will result in the following SQL:
638
+
639
+ <sql>
640
+ SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id
641
+ </sql>
642
+
643
+ h4. Using Array/Hash of Named Associations
644
+
645
+ WARNING: This method only works with +INNER JOIN+,
646
+
647
+ <br />
648
+
649
+ Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying the +:joins+ option.
650
+
651
+ For example, consider the following +Category+, +Post+, +Comments+ and +Guest+ models:
652
+
653
+ <ruby>
654
+ class Category < ActiveRecord::Base
655
+ has_many :posts
656
+ end
657
+
658
+ class Post < ActiveRecord::Base
659
+ belongs_to :category
660
+ has_many :comments
661
+ has_many :tags
662
+ end
663
+
664
+ class Comments < ActiveRecord::Base
665
+ belongs_to :post
666
+ has_one :guest
667
+ end
668
+
669
+ class Guest < ActiveRecord::Base
670
+ belongs_to :comment
671
+ end
672
+ </ruby>
673
+
674
+ Now all of the following will produce the expected join queries using +INNER JOIN+:
675
+
676
+ h5. Joining a Single Association
677
+
678
+ <ruby>
679
+ Category.all :joins => :posts
680
+ </ruby>
681
+
682
+ This produces:
683
+
684
+ <sql>
685
+ SELECT categories.* FROM categories
686
+ INNER JOIN posts ON posts.category_id = categories.id
687
+ </sql>
688
+
689
+ h5. Joining Multiple Associations
690
+
691
+ <ruby>
692
+ Post.all :joins => [:category, :comments]
693
+ </ruby>
694
+
695
+ This produces:
696
+
697
+ <sql>
698
+ SELECT posts.* FROM posts
699
+ INNER JOIN categories ON posts.category_id = categories.id
700
+ INNER JOIN comments ON comments.post_id = posts.id
701
+ </sql>
702
+
703
+ h5. Joining Nested Associations (Single Level)
704
+
705
+ <ruby>
706
+ Post.all :joins => {:comments => :guest}
707
+ </ruby>
708
+
709
+ h5. Joining Nested Associations (Multiple Level)
710
+
711
+ <ruby>
712
+ Category.all :joins => {:posts => [{:comments => :guest}, :tags]}
713
+ </ruby>
714
+
715
+ h4. Specifying Conditions on the Joined Tables
716
+
717
+ You can specify conditions on the joined tables using the regular "Array":#array-conditions and "String":#pure-string-conditions conditions. "Hash conditions":#hash-conditions provides a special syntax for specifying conditions for the joined tables:
718
+
719
+ <ruby>
720
+ time_range = (Time.now.midnight - 1.day)..Time.now.midnight
721
+ Client.all :joins => :orders, :conditions => {'orders.created_at' => time_range}
722
+ </ruby>
723
+
724
+ An alternative and cleaner syntax to this is to nest the hash conditions:
725
+
726
+ <ruby>
727
+ time_range = (Time.now.midnight - 1.day)..Time.now.midnight
728
+ Client.all :joins => :orders, :conditions => {:orders => {:created_at => time_range}}
729
+ </ruby>
730
+
731
+ This will find all clients who have orders that were created yesterday, again using a +BETWEEN+ SQL expression.
732
+
733
+ h3. Eager Loading Associations
734
+
735
+ Eager loading is the mechanism for loading the associated records of the objects returned by +Model.find+ using as few queries as possible.
736
+
737
+ <strong>N <plus> 1 queries problem</strong>
738
+
739
+ Consider the following code, which finds 10 clients and prints their postcodes:
740
+
741
+ <ruby>
742
+ clients = Client.all(:limit => 10)
743
+
744
+ clients.each do |client|
745
+ puts client.address.postcode
746
+ end
747
+ </ruby>
748
+
749
+ This code looks fine at the first sight. But the problem lies within the total number of queries executed. The above code executes 1 ( to find 10 clients ) <plus> 10 ( one per each client to load the address ) = <strong>11</strong> queries in total.
750
+
751
+ <strong>Solution to N <plus> 1 queries problem</strong>
752
+
753
+ Active Record lets you specify all the associations in advanced that are going to be loaded. This is possible by specifying the +:include+ option of the +Model.find+ call. By +:include+, Active Record ensures that all the specified associations are loaded using minimum possible number of queries.
754
+
755
+ Revisiting the above case, we could rewrite +Client.all+ to use eager load addresses:
756
+
757
+ <ruby>
758
+ clients = Client.all(:include => :address, :limit => 10)
759
+
760
+ clients.each do |client|
761
+ puts client.address.postcode
762
+ end
763
+ </ruby>
764
+
765
+ The above code will execute just <strong>2</strong> queries, as opposed to <strong>11</strong> queries in the previous case:
766
+
767
+ <sql>
768
+ SELECT * FROM clients
769
+ SELECT addresses.* FROM addresses
770
+ WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
771
+ </sql>
772
+
773
+ h4. Eager Loading Multiple Associations
774
+
775
+ Active Record lets you eager load any possible number of associations with a single +Model.find+ call by using an array, hash, or a nested hash of array/hash with the +:include+ option.
776
+
777
+ h5. Array of Multiple Associations
778
+
779
+ <ruby>
780
+ Post.all :include => [:category, :comments]
781
+ </ruby>
782
+
783
+ This loads all the posts and the associated category and comments for each post.
784
+
785
+ h5. Nested Associations Hash
786
+
787
+ <ruby>
788
+ Category.find 1, :include => {:posts => [{:comments => :guest}, :tags]}
789
+ </ruby>
790
+
791
+ The above code finds the category with id 1 and eager loads all the posts associated with the found category. Additionally, it will also eager load every posts' tags and comments. Every comment's guest association will get eager loaded as well.
792
+
793
+ h4. Specifying Conditions on Eager Loaded Associations
794
+
795
+ Even though Active Record lets you specify conditions on the eager loaded associations just like +:joins+, the recommended way is to use ":joins":#joining-tables instead.
796
+
797
+ h3. Dynamic Finders
798
+
799
+ For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +name+ on your +Client+ model for example, you get +find_by_name+ and +find_all_by_name+ for free from Active Record. If you have also have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+.
800
+
801
+ You can do +find_last_by_*+ methods too which will find the last record matching your argument.
802
+
803
+ You can specify an exclamation point (<tt>!</tt>) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+
804
+
805
+ If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_name_and_locked("Ryan", true)+.
806
+
807
+
808
+ There's another set of dynamic finders that let you find or create/initialize objects if they aren't found. These work in a similar fashion to the other finders and can be used like +find_or_create_by_name(params[:name])+. Using this will firstly perform a find and then create if the find returns +nil+. The SQL looks like this for +Client.find_or_create_by_name("Ryan")+:
809
+
810
+ <sql>
811
+ SELECT * FROM clients WHERE (clients.name = 'Ryan') LIMIT 1
812
+ BEGIN
813
+ INSERT INTO clients (name, updated_at, created_at, orders_count, locked)
814
+ VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', 0, '0')
815
+ COMMIT
816
+ </sql>
817
+
818
+ +find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will act similar to calling +new+ with the arguments you passed in. For example:
819
+
820
+ <ruby>
821
+ client = Client.find_or_initialize_by_name('Ryan')
822
+ </ruby>
823
+
824
+ will either assign an existing client object with the name "Ryan" to the client local variable, or initialize a new object similar to calling +Client.new(:name => 'Ryan')+. From here, you can modify other fields in client by calling the attribute setters on it: +client.locked = true+ and when you want to write it to the database just call +save+ on it.
825
+
826
+ h3. Finding by SQL
827
+
828
+ If you'd like to use your own SQL to find records in a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even the underlying query returns just a single record. For example you could run this query:
829
+
830
+ <ruby>
831
+ Client.find_by_sql("SELECT * FROM clients
832
+ INNER JOIN orders ON clients.id = orders.client_id
833
+ ORDER clients.created_at desc")
834
+ </ruby>
835
+
836
+ +find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
837
+
838
+ h3. +select_all+
839
+
840
+ <tt>find_by_sql</tt> has a close relative called +connection#select_all+. +select_all+ will retrieve objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
841
+
842
+ <ruby>
843
+ Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
844
+ </ruby>
845
+
846
+ h3. Existence of Objects
847
+
848
+ If you simply want to check for the existence of the object there's a method called +exists?+. This method will query the database using the same query as +find+, but instead of returning an object or collection of objects it will return either +true+ or +false+.
849
+
850
+ <ruby>
851
+ Client.exists?(1)
852
+ </ruby>
853
+
854
+ The +exists?+ method also takes multiple ids, but the catch is that it will return true if any one of those records exists.
855
+
856
+ <ruby>
857
+ Client.exists?(1,2,3)
858
+ # or
859
+ Client.exists?([1,2,3])
860
+ </ruby>
861
+
862
+ Further more, +exists+ takes a +conditions+ option much like find:
863
+
864
+ <ruby>
865
+ Client.exists?(:conditions => "first_name = 'Ryan'")
866
+ </ruby>
867
+
868
+ It's even possible to use +exists?+ without any arguments:
869
+
870
+ <ruby>
871
+ Client.exists?
872
+ </ruby>
873
+
874
+ The above returns +false+ if the +clients+ table is empty and +true+ otherwise.
875
+
876
+ h3. Calculations
877
+
878
+ This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
879
+
880
+ <tt>count</tt> takes conditions much in the same way +exists?+ does:
881
+
882
+ <ruby>
883
+ Client.count(:conditions => "first_name = 'Ryan'")
884
+ </ruby>
885
+
886
+ Which will execute:
887
+
888
+ <sql>
889
+ SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
890
+ </sql>
891
+
892
+ You can also use +:include+ or +:joins+ for this to do something a little more complex:
893
+
894
+ <ruby>
895
+ Client.count(:conditions => "clients.first_name = 'Ryan' AND orders.status = 'received'", :include => "orders")
896
+ </ruby>
897
+
898
+ Which will execute:
899
+
900
+ <sql>
901
+ SELECT count(DISTINCT clients.id) AS count_all FROM clients
902
+ LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
903
+ (clients.first_name = 'Ryan' AND orders.status = 'received')
904
+ </sql>
905
+
906
+ This code specifies +clients.first_name+ just in case one of the join tables has a field also called +first_name+ and it uses +orders.status+ because that's the name of our join table.
907
+
908
+ h4. Count
909
+
910
+ If you want to see how many records are in your model's table you could call +Client.count+ and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use +Client.count(:age)+.
911
+
912
+ For options, please see the parent section, "Calculations":#calculations.
913
+
914
+ h4. Average
915
+
916
+ If you want to see the average of a certain number in one of your tables you can call the +average+ method on the class that relates to the table. This method call will look something like this:
917
+
918
+ <ruby>
919
+ Client.average("orders_count")
920
+ </ruby>
921
+
922
+ This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
923
+
924
+ For options, please see the parent section, "Calculations":#calculations.
925
+
926
+ h4. Minimum
927
+
928
+ If you want to find the minimum value of a field in your table you can call the +minimum+ method on the class that relates to the table. This method call will look something like this:
929
+
930
+ <ruby>
931
+ Client.minimum("age")
932
+ </ruby>
933
+
934
+ For options, please see the parent section, "Calculations":#calculations.
935
+
936
+ h4. Maximum
937
+
938
+ If you want to find the maximum value of a field in your table you can call the +maximum+ method on the class that relates to the table. This method call will look something like this:
939
+
940
+ <ruby>
941
+ Client.maximum("age")
942
+ </ruby>
943
+
944
+ For options, please see the parent section, "Calculations":#calculations.
945
+
946
+ h4. Sum
947
+
948
+ If you want to find the sum of a field for all records in your table you can call the +sum+ method on the class that relates to the table. This method call will look something like this:
949
+
950
+ <ruby>
951
+ Client.sum("orders_count")
952
+ </ruby>
953
+
954
+ For options, please see the parent section, "Calculations":#calculations.
955
+
956
+ h3. Changelog
957
+
958
+ "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16
959
+
960
+ * February 7, 2009: Second version by "Pratik":credits.html#lifo
961
+ * December 29 2008: Initial version by "Ryan Bigg":credits.html#radar