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,378 @@
1
+ h2. Creating and customizing Rails Generators
2
+
3
+ Rails generators are an essential tool if you plan to improve your workflow and in this guide you will learn how to create and customize already existing generators.
4
+
5
+ In this guide you will:
6
+
7
+ * Learn how to see which generators are available in your application;
8
+ * Create a generator using templates;
9
+ * Learn how Rails searches for generators before invoking them;
10
+ * Customize your scaffold by creating new generators;
11
+ * Customize your scaffold by changing generators templates;
12
+ * Learn how to use fallbacks to avoid overwriting a huge set of generators;
13
+
14
+ endprologue.
15
+
16
+ NOTE: This guide is about Rails generators for versions >= 3.0. Rails generators from previous versions are not supported.
17
+
18
+ h3. First contact
19
+
20
+ When you create an application using the +rails+ command, you are in fact using a Rails generator. After that, you can get a list of all available generators by just invoking +script/generate+:
21
+
22
+ <shell>
23
+ $ rails myapp
24
+ $ cd myapp
25
+ $ ruby script/generate
26
+ </shell>
27
+
28
+ You will get a list of all generators that comes with Rails. If you need a detailed description, for instance about the helper generator, you can simply do:
29
+
30
+ <shell>
31
+ $ ruby script/generate helper --help
32
+ </shell>
33
+
34
+ h3. Creating your first generator
35
+
36
+ Since Rails 3.0, generators are built on top of "Thor":http://github.com/wycats/thor. Thor has a powerful options parsing and a great API for manipulating files. For instance, let's build a generator that creates an initializer file named +initializer.rb+ inside +config/initializers+.
37
+
38
+ The first step is to create a file at +RAILS_APP/lib/generators/initializer_generator.rb+ with the following content:
39
+
40
+ <ruby>
41
+ class InitializerGenerator < Rails::Generators::Base
42
+ def create_initializer_file
43
+ create_file "config/initializers/initializer.rb", "# Add initialization content here"
44
+ end
45
+ end
46
+ </ruby>
47
+
48
+ Our new generator is quite simple: it inherits from +Rails::Generators::Base+ and have one method definition. Each public method in the generator is executed when a generator is invoked. Finally, we invoke the +create_file+ method that will create a file at the given destination with the given content. If you are familiar with Rails Application Templates API, you are at home with new generators API.
49
+
50
+ To invoke our new generator, we just need to do:
51
+
52
+ <shell>
53
+ $ ruby script/generate initializer
54
+ </shell>
55
+
56
+ Before we go on, let's see our brand new generator description:
57
+
58
+ <shell>
59
+ $ ruby script/generate initializer --help
60
+ </shell>
61
+
62
+ Rails usually is able to generate good descriptions if a generator is namespaced, as +ActiveRecord::Generators::ModelGenerator+, but not in this particular case. We can solve this problem in two ways. The first one is calling +desc+ inside our generator:
63
+
64
+ <ruby>
65
+ class InitializerGenerator < Rails::Generators::Base
66
+ desc "This generator creates an initializer file at config/initializers"
67
+ def create_initializer_file
68
+ create_file "config/initializers/initializer.rb", "# Add initialization content here"
69
+ end
70
+ end
71
+ </ruby>
72
+
73
+ Now we can see the new description by invoking +--help+ in the new generator. The second way to add a description is by creating a file named +USAGE+ in the same directory as our generator. We are going to do that in the next step.
74
+
75
+ h3. Creating generators with generators
76
+
77
+ A faster way to create a generator is using the generator's generator:
78
+
79
+ <shell>
80
+ $ ruby script/generate generator initializer
81
+ create lib/generators/initializer
82
+ create lib/generators/initializer/initializer_generator.rb
83
+ create lib/generators/initializer/USAGE
84
+ create lib/generators/initializer/templates
85
+ </shell>
86
+
87
+ And it will create a new generator as follow:
88
+
89
+ <ruby>
90
+ class InitializerGenerator < Rails::Generators::NamedBase
91
+ def self.source_root
92
+ @source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
93
+ end
94
+ end
95
+ </ruby>
96
+
97
+ At first, we can notice that we are inheriting from +Rails::Generators::NamedBase+ instead of +Rails::Generators::Base+. This means that our generator expects as least one argument, which will be the name of the initializer.
98
+
99
+ We can see that by invoking the description of this new generator (don't forget to delete the old generator file):
100
+
101
+ <shell>
102
+ $ ruby script/generate initializer --help
103
+ Usage:
104
+ script/generate initializer NAME [options]
105
+ </shell>
106
+
107
+ We can also see in our new generator that it has a class method called +source_root+. This method points to where our generator templates will be placed and by default it points to the created directory under +RAILS_APP/lib/generators/initializer/templates+. In order to understand what a generator template means, let's create a file at +RAILS_APP/lib/generators/initializer/templates/initializer.rb+ with the following content:
108
+
109
+ <ruby>
110
+ # Add initialization content here
111
+
112
+ </ruby>
113
+
114
+ And now let's change the generator to copy this template when invoked:
115
+
116
+ <ruby>
117
+ class InitializerGenerator < Rails::Generators::NamedBase
118
+ def self.source_root
119
+ @source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
120
+ end
121
+
122
+ def copy_initializer_file
123
+ copy_file "initializer.rb", "config/initializers/#{file_name}.rb"
124
+ end
125
+ end
126
+ </ruby>
127
+
128
+ And let's execute our generator:
129
+
130
+ <shell>
131
+ $ ruby script/generate initializer foo
132
+ </shell>
133
+
134
+ We can see that now a initializer named foo was created at +config/initializers/foo.rb+ with the contents of our template. That means that copy_file copied a file in our source root to the destination path we gave. The method +file_name+ is automatically created when we inherit from +Rails::Generators::NamedBase+.
135
+
136
+ h3. Generators lookup
137
+
138
+ Now that we know how to create generators, we must know where Rails looks for generators before invoking them. When we invoke the initializer generator, Rails looks at the following paths in the given order:
139
+
140
+ <shell>
141
+ RAILS_APP/lib/generators
142
+ RAILS_APP/lib/rails_generators
143
+ RAILS_APP/vendor/plugins/*/lib/generators
144
+ RAILS_APP/vendor/plugins/*/lib/rails_generators
145
+ GEMS_PATH/*/lib/generators
146
+ GEMS_PATH/*/lib/rails_generators
147
+ ~/rails/generators
148
+ ~/rails/rails_generators
149
+ RAILS_GEM/lib/rails/generators
150
+ </shell>
151
+
152
+ First Rails looks for generators in your application, then in plugins and/or gems, then in your home and finally the builtin generators. One very important thing to keep in mind is that in Rails 3.0 and after it only looks for generators in gems being used in your application. So if you have rspec installed as a gem, but it's not declared in your application, Rails won't be able to invoke it.
153
+
154
+ h3. Customizing your workflow
155
+
156
+ Rails generators are flexible enough to let you customize your scaffold the way you want. In your +config/application.rb+ there is a section just for generators:
157
+
158
+ <ruby>
159
+ config.generators do |g|
160
+ g.orm :active_record
161
+ g.template_engine :erb
162
+ g.test_framework :test_unit, :fixture => true
163
+ end
164
+ </ruby>
165
+
166
+ Before we customize our workflow, let's first see how our scaffold looks like:
167
+
168
+ <shell>
169
+ $ ruby script/generate scaffold User name:string
170
+ invoke active_record
171
+ create db/migrate/20091120125558_create_users.rb
172
+ create app/models/user.rb
173
+ invoke test_unit
174
+ create test/unit/user_test.rb
175
+ create test/fixtures/users.yml
176
+ route map.resources :users
177
+ invoke scaffold_controller
178
+ create app/controllers/users_controller.rb
179
+ invoke erb
180
+ create app/views/users
181
+ create app/views/users/index.html.erb
182
+ create app/views/users/edit.html.erb
183
+ create app/views/users/show.html.erb
184
+ create app/views/users/new.html.erb
185
+ create app/views/users/_form.html.erb
186
+ create app/views/layouts/users.html.erb
187
+ invoke test_unit
188
+ create test/functional/users_controller_test.rb
189
+ invoke helper
190
+ create app/helpers/users_helper.rb
191
+ invoke test_unit
192
+ create test/unit/helpers/users_helper_test.rb
193
+ invoke stylesheets
194
+ create public/stylesheets/scaffold.css
195
+ </shell>
196
+
197
+ Looking at this output, is easy to understand how generators work on Rails 3.0 and above. The scaffold generator actually doesn't generate anything, it just invokes others to do the work. This allows us to add/replace/remove any of those invocations. For instance, the scaffold generator invokes the scaffold_controller generator, which invokes erb, test_unit and helper generators. Since each generator has a single responsibility, they are easy to reuse, avoiding code duplication.
198
+
199
+ Our first customization on the workflow will be to stop generating stylesheets and test fixtures on scaffold. We can achieve that by changing our application to the following:
200
+
201
+ <ruby>
202
+ config.generators do |g|
203
+ g.orm :active_record
204
+ g.template_engine :erb
205
+ g.test_framework :test_unit, :fixture => false
206
+ g.stylesheets false
207
+ end
208
+ </ruby>
209
+
210
+ If we generate another resource on scaffold, we can notice that neither stylesheets nor fixtures are created anymore. If you want to customize it further, for example to use +Datamapper+ and +Rspec+ instead of +ActiveRecord+ and +TestUnit+, is just a matter of adding their gems to your application and configuring your generators.
211
+
212
+ To show that, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator:
213
+
214
+ <shell>
215
+ $ ruby script/generate generator my_helper
216
+ </shell>
217
+
218
+ After that, we can delete both templates directory and the +source_root+ class method from our new generators, because we are not going to need them. So our new generator looks like the following:
219
+
220
+ <ruby>
221
+ class MyHelperGenerator < Rails::Generators::NamedBase
222
+ def create_helper_file
223
+ create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
224
+ module #{class_name}Helper
225
+ attr_reader :#{plural_name}, :#{plural_name.singularize}
226
+ end
227
+ FILE
228
+ end
229
+ end
230
+ </ruby>
231
+
232
+ We can try out our new generator by creating a helper for users:
233
+
234
+ <shell>
235
+ $ ruby script/generate my_helper users
236
+ </shell>
237
+
238
+ And it will generate the following helper file in app/helpers:
239
+
240
+ <ruby>
241
+ module UsersHelper
242
+ attr_reader :users, :user
243
+ end
244
+ </ruby>
245
+
246
+ Which is what we expected. We can now tell scaffold to use our new helper generator by configuring +config/application.rb+ once again:
247
+
248
+ <ruby>
249
+ config.generators do |g|
250
+ g.orm :active_record
251
+ g.template_engine :erb
252
+ g.test_framework :test_unit, :fixture => false
253
+ g.stylesheets false
254
+ g.helper :my_helper
255
+ end
256
+ </ruby>
257
+
258
+ And see it in action when invoking generator once again:
259
+
260
+ <shell>
261
+ $ ruby script/generate scaffold Post body:text
262
+ [...]
263
+ invoke my_helper
264
+ create app/helpers/posts_helper.rb
265
+ </shell>
266
+
267
+ We can notice on the output that our new helper was invoked instead of the Rails default. However one thing is missing, which is tests for our new generator and to do that, we are going to reuse old helpers test generators.
268
+
269
+ Since Rails 3.0, this is easy to do due to the hooks concept. Our new helper does not need to be focused in one specific test framework, it can simply provide a hook and a test framework just need to implement this hook in order to be compatible.
270
+
271
+ To do that, we can change your generator to the following:
272
+
273
+ <ruby>
274
+ class MyHelperGenerator < Rails::Generators::NamedBase
275
+ def create_helper_file
276
+ create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
277
+ module #{class_name}Helper
278
+ attr_reader :#{plural_name}, :#{plural_name.singularize}
279
+ end
280
+ FILE
281
+ end
282
+
283
+ hook_for :test_framework
284
+ end
285
+ </ruby>
286
+
287
+ Now, when the helper generator is invoked and let's say test unit is configured as test framework, it will try to invoke both +MyHelper::Generators::TestUnitGenerator+ and +TestUnit::Generators::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails hook. To do that, we just need to add:
288
+
289
+ <ruby>
290
+ # Search for :helper instead of :my_helper
291
+ hook_for :test_framework, :as => :helper
292
+ </ruby>
293
+
294
+ And now you can re-run scaffold for another resource and see it generating tests as well!
295
+
296
+ h3. Customizing your workflow by changing generators templates
297
+
298
+ In the step above, we simply wanted to add a line to the generated helper, without adding any extra functionality. There is a simpler way to do that, and it's by replacing the templates of already existing generators.
299
+
300
+ In Rails 3.0 and above, generators does not look only in the source root for templates, they also search for templates in other paths. And one of them is inside +RAILS_APP/lib/templates+. Since we want to customize +Rails::Generators::HelperGenerator+, we can do that by simple making a template copy inside +RAILS_APP/lib/templates/rails/helper+ with the name +helper.rb+. So let's create such file with the following content:
301
+
302
+ <erb>
303
+ module <%= class_name %>Helper
304
+ attr_reader :<%= plural_name %>, <%= plural_name.singularize %>
305
+ end
306
+ </erb>
307
+
308
+ So now we can revert the changes in +config/application.rb+:
309
+
310
+ <ruby>
311
+ config.generators do |g|
312
+ g.orm :active_record
313
+ g.template_engine :erb
314
+ g.test_framework :test_unit, :fixture => false
315
+ g.stylesheets false
316
+ end
317
+ </ruby>
318
+
319
+ If you generate another resource, you can see that we got exactly the same result! This is useful if you want to customize your scaffold templates and/or layout by just creating +edit.html.erb+, +index.html.erb+ and so on inside +RAILS_APP/lib/templates/erb/scaffold+.
320
+
321
+ h3. Adding generators fallbacks
322
+
323
+ One last feature about generators which is quite useful for plugin generators is fallbacks. For example, imagine that you want to add a feature on top of TestUnit test framework, like "shoulda":http://github.com/thoughtbot/shoulda does. Since TestUnit already implements all generators required by Rails and shoulda just want to overwrite part of it, there is no need for shoulda to reimplement some generators again, they can simply tell Rails to use a +TestUnit+ generator if none was found under +Shoulda+ namespace.
324
+
325
+ We can easily simulate this behavior by changing our +config/application.rb+ once again:
326
+
327
+ <ruby>
328
+ config.generators do |g|
329
+ g.orm :active_record
330
+ g.template_engine :erb
331
+ g.test_framework :shoulda, :fixture => false
332
+ g.stylesheets false
333
+ end
334
+ </ruby>
335
+
336
+ And at the end of the same file:
337
+
338
+ <ruby>
339
+ require 'rails/generators'
340
+ Rails::Generators.fallbacks[:shoulda] = :test_unit
341
+ </ruby>
342
+
343
+ Now, if create a Comment scaffold, you will see that shoulda generators are being invoked, and at the end, they are just falling back to test unit generators:
344
+
345
+ <shell>
346
+ $ ruby script/generate scaffold Comment body:text
347
+ invoke active_record
348
+ create db/migrate/20091120151323_create_comments.rb
349
+ create app/models/comment.rb
350
+ invoke shoulda
351
+ create test/unit/comment_test.rb
352
+ create test/fixtures/comments.yml
353
+ route map.resources :comments
354
+ invoke scaffold_controller
355
+ create app/controllers/comments_controller.rb
356
+ invoke erb
357
+ create app/views/comments
358
+ create app/views/comments/index.html.erb
359
+ create app/views/comments/edit.html.erb
360
+ create app/views/comments/show.html.erb
361
+ create app/views/comments/new.html.erb
362
+ create app/views/comments/_form.html.erb
363
+ create app/views/layouts/comments.html.erb
364
+ invoke shoulda
365
+ create test/functional/comments_controller_test.rb
366
+ invoke my_helper
367
+ create app/helpers/comments_helper.rb
368
+ invoke shoulda
369
+ create test/unit/helpers/comments_helper_test.rb
370
+ </shell>
371
+
372
+ Such tool allows your generators to have single responsibility, increasing the code reuse and reducing the amount of code duplication.
373
+
374
+ h3. Changelog
375
+
376
+ "Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/102
377
+
378
+ * November 20, 2009: First release version by José Valim
@@ -0,0 +1,1310 @@
1
+ h2. Getting Started with Rails
2
+
3
+ This guide covers getting up and running with Ruby on Rails. After reading it, you should be familiar with:
4
+
5
+ * Installing Rails, creating a new Rails application, and connecting your application to a database
6
+ * The general layout of a Rails application
7
+ * The basic principles of MVC (Model, View Controller) and RESTful design
8
+ * How to quickly generate the starting pieces of a Rails application.
9
+
10
+ endprologue.
11
+
12
+ WARNING. This Guide is based on Rails 2.3.3. Some of the code shown here will not work in other versions of Rails.
13
+
14
+ h3. This Guide Assumes
15
+
16
+ This guide is designed for beginners who want to get started with a Rails application from scratch. It does not assume that you have any prior experience with Rails. However, to get the most out of it, you need to have some prerequisites installed:
17
+
18
+ * The "Ruby":http://www.ruby-lang.org/en/downloads language
19
+ * The "RubyGems":http://rubyforge.org/frs/?group_id=126 packaging system
20
+ * A working installation of "SQLite":http://www.sqlite.org (preferred), "MySQL":http://www.mysql.com, or "PostgreSQL":http://www.postgresql.org
21
+
22
+ It is highly recommended that you *familiarize yourself with Ruby before diving into Rails*. You will find it much easier to follow what's going on with a Rails application if you understand basic Ruby syntax. Rails isn't going to magically revolutionize the way you write web applications if you have no experience with the language it uses. There are some good free resources on the internet for learning Ruby, including:
23
+
24
+ * "Mr. Neighborly's Humble Little Ruby Book":http://www.humblelittlerubybook.com
25
+ * "Programming Ruby":http://www.ruby-doc.org/docs/ProgrammingRuby/
26
+ * "Why's (Poignant) Guide to Ruby":http://mislav.uniqpath.com/poignant-guide/
27
+
28
+ h3. What is Rails?
29
+
30
+ Rails is a web development framework written in the Ruby language. It is designed to make programming web applications easier by making assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than many other languages and frameworks. Longtime Rails developers also report that it makes web application development more fun.
31
+
32
+ Rails is opinionated software. That is, it assumes that there is a best way to do things, and it's designed to encourage that best way - and in some cases to discourage alternatives. If you learn "The Rails Way" you'll probably discover a tremendous increase in productivity. If you persist in bringing old habits from other languages to your Rails development, and trying to use patterns you learned elsewhere, you may have a less happy experience.
33
+
34
+ The Rails philosophy includes several guiding principles:
35
+
36
+ * DRY - "Don't Repeat Yourself" - suggests that writing the same code over and over again is a bad thing.
37
+ * Convention Over Configuration - means that Rails makes assumptions about what you want to do and how you're going to do it, rather than letting you tweak every little thing through endless configuration files.
38
+ * REST is the best pattern for web applications - organizing your application around resources and standard HTTP verbs is the fastest way to go.
39
+
40
+ h4. The MVC Architecture
41
+
42
+ Rails is organized around the Model, View, Controller architecture, usually just called MVC. MVC benefits include:
43
+
44
+ * Isolation of business logic from the user interface
45
+ * Ease of keeping code DRY
46
+ * Making it clear where different types of code belong for easier maintenance
47
+
48
+ h5. Models
49
+
50
+ A model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, one table in your database will correspond to one model in your application. The bulk of your application's business logic will be concentrated in the models.
51
+
52
+ h5. Views
53
+
54
+ Views represent the user interface of your application. In Rails, views are often HTML files with embedded Ruby code that perform tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application.
55
+
56
+ h5. Controllers
57
+
58
+ Controllers provide the "glue" between models and views. In Rails, controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.
59
+
60
+ h4. The Components of Rails
61
+
62
+ Rails provides a full stack of components for creating web applications, including:
63
+
64
+ * Action Controller
65
+ * Action View
66
+ * Active Record
67
+ * Action Mailer
68
+ * Active Resource
69
+ * Railties
70
+ * Active Support
71
+
72
+ h5. Action Controller
73
+
74
+ Action Controller is the component that manages the controllers in a Rails application. The Action Controller framework processes incoming requests to a Rails application, extracts parameters, and dispatches them to the intended action. Services provided by Action Controller include session management, template rendering, and redirect management.
75
+
76
+ h5. Action View
77
+
78
+ Action View manages the views of your Rails application. It can create both HTML and XML output by default. Action View manages rendering templates, including nested and partial templates, and includes built-in AJAX support.
79
+
80
+ h5. Active Record
81
+
82
+ Active Record is the base for the models in a Rails application. It provides database independence, basic CRUD functionality, advanced finding capabilities, and the ability to relate models to one another, among other services.
83
+
84
+ h5. Action Mailer
85
+
86
+ Action Mailer is a framework for building e-mail services. You can use Action Mailer to send emails based on flexible templates, or to receive and process incoming email.
87
+
88
+ h5. Active Resource
89
+
90
+ Active Resource provides a framework for managing the connection between business objects and RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics.
91
+
92
+ h5. Railties
93
+
94
+ Railties is the core Rails code that builds new Rails applications and glues the various frameworks together in any Rails application.
95
+
96
+ h5. Active Support
97
+
98
+ Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in the Rails, both by the core code and by your applications.
99
+
100
+ h4. REST
101
+
102
+ The foundation of the RESTful architecture is generally considered to be Roy Fielding's doctoral thesis, "Architectural Styles and the Design of Network-based Software Architectures":http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm. Fortunately, you need not read this entire document to understand how REST works in Rails. REST, an acronym for Representational State Transfer, boils down to two main principles for our purposes:
103
+
104
+ * Using resource identifiers (which, for the purposes of discussion, you can think of as URLs) to represent resources
105
+ * Transferring representations of the state of that resource between system components.
106
+
107
+ For example, to a Rails application a request such as this:
108
+
109
+ <tt>DELETE /photos/17</tt>
110
+
111
+ would be understood to refer to a photo resource with the ID of 17, and to indicate a desired action - deleting that resource. REST is a natural style for the architecture of web applications, and Rails makes it even more natural by using conventions to shield you from some of the RESTful complexities and browser quirks.
112
+
113
+ If you'd like more details on REST as an architectural style, these resources are more approachable than Fielding's thesis:
114
+
115
+ * "A Brief Introduction to REST":http://www.infoq.com/articles/rest-introduction by Stefan Tilkov
116
+ * "An Introduction to REST":http://bitworking.org/news/373/An-Introduction-to-REST (video tutorial) by Joe Gregorio
117
+ * "Representational State Transfer":http://en.wikipedia.org/wiki/Representational_State_Transfer article in Wikipedia
118
+ * "How to GET a Cup of Coffee":http://www.infoq.com/articles/webber-rest-workflow by Jim Webber, Savas Parastatidis & Ian Robinson
119
+
120
+ h3. Creating a New Rails Project
121
+
122
+ If you follow this guide, you'll create a Rails project called <tt>blog</tt>, a (very) simple weblog. Before you can start building the application, you need to make sure that you have Rails itself installed.
123
+
124
+ h4. Installing Rails
125
+
126
+ In most cases, the easiest way to install Rails is to take advantage of RubyGems:
127
+
128
+ <shell>
129
+ $ gem install rails
130
+ </shell>
131
+
132
+ NOTE. There are some special circumstances in which you might want to use an alternate installation strategy:
133
+
134
+ * If you're working on Windows, you may find it easier to install Instant Rails. Be aware, though, that "Instant Rails":http://instantrails.rubyforge.org/wiki/wiki.pl releases tend to lag seriously behind the actual Rails version. Also, you will find that Rails development on Windows is overall less pleasant than on other operating systems. If at all possible, we suggest that you install a Linux virtual machine and use that for Rails development, instead of using Windows.
135
+ * If you want to keep up with cutting-edge changes to Rails, you'll want to clone the "Rails source code":http://github.com/rails/rails/tree/master from github. This is not recommended as an option for beginners, though.
136
+
137
+ WARNING. As of mid-2009, cloning the master branch will get you preliminary Rails 3.0 code. To follow along with this guide, you should clone the 2-3-stable branch instead.
138
+
139
+ h4. Creating the Blog Application
140
+
141
+ Open a terminal, navigate to a folder where you have rights to create files, and type:
142
+
143
+ <shell>
144
+ $ rails blog
145
+ </shell>
146
+
147
+ This will create a Rails application that uses a SQLite database for data storage. If you prefer to use MySQL, run this command instead:
148
+
149
+ <shell>
150
+ $ rails blog -d mysql
151
+ </shell>
152
+
153
+ And if you're using PostgreSQL for data storage, run this command:
154
+
155
+ <shell>
156
+ $ rails blog -d postgresql
157
+ </shell>
158
+
159
+ TIP: You can see all of the switches that the Rails application builder accepts by running <tt>rails -h</tt>.
160
+
161
+ After you create the blog application, switch to its folder to continue work directly in that application:
162
+
163
+ <shell>
164
+ $ cd blog
165
+ </shell>
166
+
167
+ In any case, Rails will create a folder in your working directory called <tt>blog</tt>. Open up that folder and explore its contents. Most of the work in this tutorial will happen in the <tt>app/</tt> folder, but here's a basic rundown on the function of each folder that Rails creates in a new application by default:
168
+
169
+ |_.File/Folder|_.Purpose|
170
+ |README|This is a brief instruction manual for your application. Use it to tell others what your application does, how to set it up, and so on.|
171
+ |Rakefile|This file contains batch jobs that can be run from the terminal.|
172
+ |app/|Contains the controllers, models, and views for your application. You'll focus on this folder for the remainder of this guide.|
173
+ |config/|Configure your application's runtime rules, routes, database, and more.|
174
+ |db/|Shows your current database schema, as well as the database migrations. You'll learn about migrations shortly.|
175
+ |doc/|In-depth documentation for your application.|
176
+ |lib/|Extended modules for your application (not covered in this guide).|
177
+ |log/|Application log files.|
178
+ |public/|The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go.|
179
+ |script/|Scripts provided by Rails to do recurring tasks, such as benchmarking, plugin installation, and starting the console or the web server.|
180
+ |test/|Unit tests, fixtures, and other test apparatus. These are covered in "Testing Rails Applications":testing.html|
181
+ |tmp/|Temporary files|
182
+ |vendor/|A place for third-party code. In a typical Rails application, this includes Ruby Gems, the Rails source code (if you install it into your project) and plugins containing additional prepackaged functionality.|
183
+
184
+ h4. Configuring a Database
185
+
186
+ Just about every Rails application will interact with a database. The database to use is specified in a configuration file, +config/database.yml+.
187
+ If you open this file in a new Rails application, you'll see a default database configuration using SQLite. The file contains sections for three different environments in which Rails can run by default:
188
+
189
+ * The +development+ environment is used on your development computer as you interact manually with the application
190
+ * The +test+ environment is used to run automated tests
191
+ * The +production+ environment is used when you deploy your application for the world to use.
192
+
193
+ h5. Configuring a SQLite Database
194
+
195
+ Rails comes with built-in support for "SQLite":http://www.sqlite.org, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.
196
+
197
+ Here's the section of the default configuration file with connection information for the development environment:
198
+
199
+ <yaml>
200
+ development:
201
+ adapter: sqlite3
202
+ database: db/development.sqlite3
203
+ pool: 5
204
+ timeout: 5000
205
+ </yaml>
206
+
207
+ If you don't have any database set up, SQLite is the easiest to get installed. If you're on OS X 10.5 or greater on a Mac, you already have it. Otherwise, you can install it using RubyGems:
208
+
209
+ <shell>
210
+ $ gem install sqlite3-ruby
211
+ </shell>
212
+
213
+ h5. Configuring a MySQL Database
214
+
215
+ If you choose to use MySQL, your +config/database.yml+ will look a little different. Here's the development section:
216
+
217
+ <yaml>
218
+ development:
219
+ adapter: mysql
220
+ encoding: utf8
221
+ database: blog_development
222
+ pool: 5
223
+ username: root
224
+ password:
225
+ socket: /tmp/mysql.sock
226
+ </yaml>
227
+
228
+ If your development computer's MySQL installation includes a root user with an empty password, this configuration should work for you. Otherwise, change the username and password in the +development+ section as appropriate.
229
+
230
+ h5. Configuring a PostgreSQL Database
231
+
232
+ If you choose to use PostgreSQL, your +config/database.yml+ will be customized to use PostgreSQL databases:
233
+
234
+ <yaml>
235
+ development:
236
+ adapter: postgresql
237
+ encoding: unicode
238
+ database: blog_development
239
+ pool: 5
240
+ username: blog
241
+ password:
242
+ </yaml>
243
+
244
+ Change the username and password in the +development+ section as appropriate.
245
+
246
+ h4. Creating the Database
247
+
248
+ Now that you have your database configured, it's time to have Rails create an empty database for you. You can do this by running a rake command:
249
+
250
+ <shell>
251
+ $ rake db:create
252
+ </shell>
253
+
254
+ NOTE. Rake is a general-purpose command-runner that Rails uses for many things. You can see the list of available rake commands in your application by running +rake -T+.
255
+
256
+ h3. Hello, Rails!
257
+
258
+ One of the traditional places to start with a new language is by getting some text up on screen quickly. To do that in Rails, you need to create at minimum a controller and a view. Fortunately, you can do that in a single command. Enter this command in your terminal:
259
+
260
+ <shell>
261
+ $ script/generate controller home index
262
+ </shell>
263
+
264
+ TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +script+ commands to Ruby: +ruby script/generate controller home index+.
265
+
266
+ Rails will create several files for you, including +app/views/home/index.html.erb+. This is the template that will be used to display the results of the +index+ action (method) in the +home+ controller. Open this file in your text editor and edit it to contain a single line of code:
267
+
268
+ <code class="html">
269
+ <h1>Hello, Rails!</h1>
270
+ </code>
271
+
272
+ h4. Starting up the Web Server
273
+
274
+ You actually have a functional Rails application already - after running only two commands! To see it, you need to start a web server on your development machine. You can do this by running another command:
275
+
276
+ <shell>
277
+ $ script/server
278
+ </shell>
279
+
280
+ This will fire up an instance of the Mongrel web server by default (Rails can also use several other web servers). To see your application in action, open a browser window and navigate to +http://localhost:3000+. You should see Rails' default information page:
281
+
282
+ !images/rails_welcome.png(Welcome Aboard screenshot)!
283
+
284
+ TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. In development mode, Rails does not generally require you to stop the server; changes you make in files will be automatically picked up by the server.
285
+
286
+ The "Welcome Aboard" page is the _smoke test_ for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. To view the page you just created, navigate to +http://localhost:3000/home/index+.
287
+
288
+ h4. Setting the Application Home Page
289
+
290
+ You'd probably like to replace the "Welcome Aboard" page with your own application's home page. The first step to doing this is to delete the default page from your application:
291
+
292
+ <shell>
293
+ $ rm public/index.html
294
+ </shell>
295
+
296
+ Now, you have to tell Rails where your actual home page is located. Open the file +config/routes.rb+ in your editor. This is your application's, _routing file_, which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. At the bottom of the file you'll see the _default routes_:
297
+
298
+ <ruby>
299
+ map.connect ':controller/:action/:id'
300
+ map.connect ':controller/:action/:id.:format'
301
+ </ruby>
302
+
303
+ The default routes handle simple requests such as +/home/index+: Rails translates that into a call to the +index+ action in the +home+ controller. As another example, +/posts/edit/1+ would run the +edit+ action in the +posts+ controller with an +id+ of 1.
304
+
305
+ To hook up your home page, you need to add another line to the routing file, above the default routes:
306
+
307
+ <ruby>
308
+ map.root :controller => "home"
309
+ </ruby>
310
+
311
+ This line illustrates one tiny bit of the "convention over configuration" approach: if you don't specify an action, Rails assumes the +index+ action.
312
+
313
+ Now if you navigate to +http://localhost:3000+ in your browser, you'll see the +home/index+ view.
314
+
315
+ NOTE. For more information about routing, refer to "Rails Routing from the Outside In":routing.html.
316
+
317
+ h3. Getting Up and Running Quickly with Scaffolding
318
+
319
+ Rails _scaffolding_ is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.
320
+
321
+ h3. Creating a Resource
322
+
323
+ In the case of the blog application, you can start by generating a scaffolded Post resource: this will represent a single blog posting. To do this, enter this command in your terminal:
324
+
325
+ <shell>
326
+ $ script/generate scaffold Post name:string title:string content:text
327
+ </shell>
328
+
329
+ NOTE. While scaffolding will get you up and running quickly, the "one size fits all" code that it generates is unlikely to be a perfect fit for your application. In most cases, you'll need to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch.
330
+
331
+ The scaffold generator will build 14 files in your application, along with some folders, and edit one more. Here's a quick overview of what it creates:
332
+
333
+ |_.File |_.Purpose|
334
+ |app/models/post.rb |The Post model|
335
+ |db/migrate/20090113124235_create_posts.rb |Migration to create the posts table in your database (your name will include a different timestamp)|
336
+ |app/views/posts/index.html.erb |A view to display an index of all posts |
337
+ |app/views/posts/show.html.erb |A view to display a single post|
338
+ |app/views/posts/new.html.erb |A view to create a new post|
339
+ |app/views/posts/edit.html.erb |A view to edit an existing post|
340
+ |app/views/layouts/posts.html.erb |A view to control the overall look and feel of the other posts views|
341
+ |public/stylesheets/scaffold.css |Cascading style sheet to make the scaffolded views look better|
342
+ |app/controllers/posts_controller.rb |The Posts controller|
343
+ |test/functional/posts_controller_test.rb |Functional testing harness for the posts controller|
344
+ |app/helpers/posts_helper.rb |Helper functions to be used from the posts views|
345
+ |config/routes.rb |Edited to include routing information for posts|
346
+ |test/fixtures/posts.yml |Dummy posts for use in testing|
347
+ |test/unit/post_test.rb |Unit testing harness for the posts model|
348
+ |test/unit/helpers/posts_helper_test.rb |Unit testing harness for the posts helper|
349
+
350
+ h4. Running a Migration
351
+
352
+ One of the products of the +script/generate scaffold+ command is a _database migration_. Migrations are Ruby classes that are designed to make it simple to create and modify database tables. Rails uses rake commands to run migrations, and it's possible to undo a migration after it's been applied to your database. Migration filenames include a timestamp to ensure that they're processed in the order that they were created.
353
+
354
+ If you look in the +db/migrate/20090113124235_create_posts.rb+ file (remember, yours will have a slightly different name), here's what you'll find:
355
+
356
+ <ruby>
357
+ class CreatePosts < ActiveRecord::Migration
358
+ def self.up
359
+ create_table :posts do |t|
360
+ t.string :name
361
+ t.string :title
362
+ t.text :content
363
+
364
+ t.timestamps
365
+ end
366
+ end
367
+
368
+ def self.down
369
+ drop_table :posts
370
+ end
371
+ end
372
+ </ruby>
373
+
374
+ If you were to translate that into words, it says something like: when this migration is run, create a table named +posts+ with two string columns (+name+ and +title+) and a text column (+content+), and generate timestamp fields to track record creation and updating. You can learn the detailed syntax for migrations in the "Rails Database Migrations":migrations.html guide.
375
+
376
+ At this point, you can use a rake command to run the migration:
377
+
378
+ <shell>
379
+ $ rake db:migrate
380
+ </shell>
381
+
382
+ Remember, you can't run migrations before running +rake db:create+ to create your database, as we covered earlier.
383
+
384
+ NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file.
385
+
386
+ h4. Adding a Link
387
+
388
+ To hook the posts up to the home page you've already created, you can add a link to the home page. Open +app/views/home/index.html.erb+ and modify it as follows:
389
+
390
+ <code lang="ruby">
391
+ <h1>Hello, Rails!</h1>
392
+ <%= link_to "My Blog", posts_path %>
393
+ </code>
394
+
395
+ The +link_to+ method is one of Rails' built-in view helpers. It creates a hyperlink based on text to display and where to go - in this case, to the path for posts.
396
+
397
+ h4. Working with Posts in the Browser
398
+
399
+ Now you're ready to start working with posts. To do that, navigate to +http://localhost:3000+ and then click the "My Blog" link:
400
+
401
+ !images/posts_index.png(Posts Index screenshot)!
402
+
403
+ This is the result of Rails rendering the +index+ view of your posts. There aren't currently any posts in the database, but if you click the +New Post+ link you can create one. After that, you'll find that you can edit posts, look at their details, or destroy them. All of the logic and HTML to handle this was built by the single +script/generate scaffold+ command.
404
+
405
+ TIP: In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop and restart the web server.
406
+
407
+ Congratulations, you're riding the rails! Now it's time to see how it all works.
408
+
409
+ h4. The Model
410
+
411
+ The model file, +app/models/post.rb+ is about as simple as it can get:
412
+
413
+ <ruby>
414
+ class Post < ActiveRecord::Base
415
+ end
416
+ </ruby>
417
+
418
+ There isn't much to this file - but note that the +Post+ class inherits from +ActiveRecord::Base+. Active Record supplies a great deal of functionality to your Rails models for free, including basic database CRUD (Create, Read, Update, Destroy) operations, data validation, as well as sophisticated search support and the ability to relate multiple models to one another.
419
+
420
+ h4. Adding Some Validation
421
+
422
+ Rails includes methods to help you validate the data that you send to models. Open the +app/models/post.rb+ file and edit it:
423
+
424
+ <ruby>
425
+ class Post < ActiveRecord::Base
426
+ validates_presence_of :name, :title
427
+ validates_length_of :title, :minimum => 5
428
+ end
429
+ </ruby>
430
+
431
+ These changes will ensure that all posts have a name and a title, and that the title is at least five characters long. Rails can validate a variety of conditions in a model, including the presence or uniqueness of columns, their format, and the existence of associated objects.
432
+
433
+ h4. Using the Console
434
+
435
+ To see your validations in action, you can use the console. The console is a command-line tool that lets you execute Ruby code in the context of your application:
436
+
437
+ <shell>
438
+ $ script/console
439
+ </shell>
440
+
441
+ After the console loads, you can use it to work with your application's models:
442
+
443
+ <shell>
444
+ >> p = Post.create(:content => "A new post")
445
+ => #<Post id: nil, name: nil, title: nil, content: "A new post",
446
+ created_at: nil, updated_at: nil>
447
+ >> p.save
448
+ => false
449
+ >> p.errors
450
+ => #<ActiveRecord::Errors:0x23bcf0c @base=#<Post id: nil, name: nil,
451
+ title: nil, content: "A new post", created_at: nil, updated_at: nil>,
452
+ @errors={"name"=>["can't be blank"], "title"=>["can't be blank",
453
+ "is too short (minimum is 5 characters)"]}>
454
+ </shell>
455
+
456
+ This code shows creating a new +Post+ instance, attempting to save it and getting +false+ for a return value (indicating that the save failed), and inspecting the +errors+ of the post.
457
+
458
+ TIP: Unlike the development web server, the console does not automatically load your code afresh for each line. If you make changes to your models while the console is open, type +reload!+ at the console prompt to load them.
459
+
460
+ h4. Listing All Posts
461
+
462
+ The easiest place to start looking at functionality is with the code that lists all posts. Open the file +app/controllers/posts_controller.rb + and look at the +index+ action:
463
+
464
+ <ruby>
465
+ def index
466
+ @posts = Post.all
467
+
468
+ respond_to do |format|
469
+ format.html # index.html.erb
470
+ format.xml { render :xml => @posts }
471
+ end
472
+ end
473
+ </ruby>
474
+
475
+ This code sets the +@posts+ instance variable to an array of all posts in the database. +Post.find(:all)+ or +Post.all+ calls the +Post+ model to return all of the posts that are currently in the database, with no limiting conditions.
476
+
477
+ TIP: For more information on finding records with Active Record, see "Active Record Query Interface":active_record_querying.html.
478
+
479
+ The +respond_to+ block handles both HTML and XML calls to this action. If you browse to +http://localhost:3000/posts.xml+, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's +app/views/posts/index.html.erb+:
480
+
481
+ <erb>
482
+ <h1>Listing posts</h1>
483
+
484
+ <table>
485
+ <tr>
486
+ <th>Name</th>
487
+ <th>Title</th>
488
+ <th>Content</th>
489
+ </tr>
490
+
491
+ <% @posts.each do |post| %>
492
+ <tr>
493
+ <td><%=h post.name %></td>
494
+ <td><%=h post.title %></td>
495
+ <td><%=h post.content %></td>
496
+ <td><%= link_to 'Show', post %></td>
497
+ <td><%= link_to 'Edit', edit_post_path(post) %></td>
498
+ <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?',
499
+ :method => :delete %></td>
500
+ </tr>
501
+ <% end %>
502
+ </table>
503
+
504
+ <br />
505
+
506
+ <%= link_to 'New post', new_post_path %>
507
+ </erb>
508
+
509
+ This view iterates over the contents of the +@posts+ array to display content and links. A few things to note in the view:
510
+
511
+ * +h+ is a Rails helper method to sanitize displayed data, preventing cross-site scripting attacks
512
+ * +link_to+ builds a hyperlink to a particular destination
513
+ * +edit_post_path+ is a helper that Rails provides as part of RESTful routing. You'll see a variety of these helpers for the different actions that the controller includes.
514
+
515
+ TIP: For more details on the rendering process, see "Layouts and Rendering in Rails":layouts_and_rendering.html.
516
+
517
+ h4. Customizing the Layout
518
+
519
+ The view is only part of the story of how HTML is displayed in your web browser. Rails also has the concept of +layouts+, which are containers for views. When Rails renders a view to the browser, it does so by putting the view's HTML into a layout's HTML. The +script/generate scaffold+ command automatically created a default layout, +app/views/layouts/posts.html.erb+, for the posts. Open this layout in your editor and modify the +body+ tag:
520
+
521
+ <erb>
522
+ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
523
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
524
+
525
+ <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
526
+ <head>
527
+ <meta http-equiv="content-type"
528
+ content="text/html;charset=UTF-8" />
529
+ <title>Posts: <%= controller.action_name %></title>
530
+ <%= stylesheet_link_tag 'scaffold' %>
531
+ </head>
532
+ <body style="background: #EEEEEE;">
533
+
534
+ <p style="color: green"><%= flash[:notice] %></p>
535
+
536
+ <%= yield %>
537
+
538
+ </body>
539
+ </html>
540
+ </erb>
541
+
542
+ Now when you refresh the +/posts+ page, you'll see a gray background to the page. This same gray background will be used throughout all the views for posts.
543
+
544
+ h4. Creating New Posts
545
+
546
+ Creating a new post involves two actions. The first is the +new+ action, which instantiates an empty +Post+ object:
547
+
548
+ <ruby>
549
+ def new
550
+ @post = Post.new
551
+
552
+ respond_to do |format|
553
+ format.html # new.html.erb
554
+ format.xml { render :xml => @post }
555
+ end
556
+ end
557
+ </ruby>
558
+
559
+ The +new.html.erb+ view displays this empty Post to the user:
560
+
561
+ <erb>
562
+ <h1>New post</h1>
563
+
564
+ <% form_for(@post) do |f| %>
565
+ <%= f.error_messages %>
566
+
567
+ <p>
568
+ <%= f.label :name %><br />
569
+ <%= f.text_field :name %>
570
+ </p>
571
+ <p>
572
+ <%= f.label :title %><br />
573
+ <%= f.text_field :title %>
574
+ </p>
575
+ <p>
576
+ <%= f.label :content %><br />
577
+ <%= f.text_area :content %>
578
+ </p>
579
+ <p>
580
+ <%= f.submit "Create" %>
581
+ </p>
582
+ <% end %>
583
+
584
+ <%= link_to 'Back', posts_path %>
585
+ </erb>
586
+
587
+ The +form_for+ block is used to create an HTML form. Within this block, you have access to methods to build various controls on the form. For example, +f.text_field :name+ tells Rails to create a text input on the form, and to hook it up to the +name+ attribute of the instance being displayed. You can only use these methods with attributes of the model that the form is based on (in this case +name+, +title+, and +content+). Rails uses +form_for+ in preference to having you write raw HTML because the code is more succinct, and because it explicitly ties the form to a particular model instance.
588
+
589
+ TIP: If you need to create an HTML form that displays arbitrary fields, not tied to a model, you should use the +form_tag+ method, which provides shortcuts for building forms that are not necessarily tied to a model instance.
590
+
591
+ When the user clicks the +Create+ button on this form, the browser will send information back to the +create+ method of the controller (Rails knows to call the +create+ method because the form is sent with an HTTP POST request; that's one of the conventions that I mentioned earlier):
592
+
593
+ <ruby>
594
+ def create
595
+ @post = Post.new(params[:post])
596
+
597
+ respond_to do |format|
598
+ if @post.save
599
+ flash[:notice] = 'Post was successfully created.'
600
+ format.html { redirect_to(@post) }
601
+ format.xml { render :xml => @post, :status => :created,
602
+ :location => @post }
603
+ else
604
+ format.html { render :action => "new" }
605
+ format.xml { render :xml => @post.errors,
606
+ :status => :unprocessable_entity }
607
+ end
608
+ end
609
+ end
610
+ </ruby>
611
+
612
+ The +create+ action instantiates a new Post object from the data supplied by the user on the form, which Rails makes available in the +params+ hash. After saving the new post, it uses +flash[:notice]+ to create an informational message for the user, and redirects to the show action for the post. If there's any problem, the +create+ action just shows the +new+ view a second time, with any error messages.
613
+
614
+ Rails provides the +flash+ hash (usually just called the Flash) so that messages can be carried over to another action, providing the user with useful information on the status of their request. In the case of +create+, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon Rails saves the record. The Flash carries over a message to the next action, so that when the user is redirected back to the +show+ action, they are presented with a message saying "Post was successfully created."
615
+
616
+ h4. Showing an Individual Post
617
+
618
+ When you click the +show+ link for a post on the index page, it will bring you to a URL like +http://localhost:3000/posts/1+. Rails interprets this as a call to the +show+ action for the resource, and passes in +1+ as the +:id+ parameter. Here's the +show+ action:
619
+
620
+ <ruby>
621
+ def show
622
+ @post = Post.find(params[:id])
623
+
624
+ respond_to do |format|
625
+ format.html # show.html.erb
626
+ format.xml { render :xml => @post }
627
+ end
628
+ end
629
+ </ruby>
630
+
631
+ The +show+ action uses +Post.find+ to search for a single record in the database by its id value. After finding the record, Rails displays it by using +show.html.erb+:
632
+
633
+ <erb>
634
+ <p>
635
+ <b>Name:</b>
636
+ <%=h @post.name %>
637
+ </p>
638
+
639
+ <p>
640
+ <b>Title:</b>
641
+ <%=h @post.title %>
642
+ </p>
643
+
644
+ <p>
645
+ <b>Content:</b>
646
+ <%=h @post.content %>
647
+ </p>
648
+
649
+
650
+ <%= link_to 'Edit', edit_post_path(@post) %> |
651
+ <%= link_to 'Back', posts_path %>
652
+ </erb>
653
+
654
+ h4. Editing Posts
655
+
656
+ Like creating a new post, editing a post is a two-part process. The first step is a request to +edit_post_path(@post)+ with a particular post. This calls the +edit+ action in the controller:
657
+
658
+ <ruby>
659
+ def edit
660
+ @post = Post.find(params[:id])
661
+ end
662
+ </ruby>
663
+
664
+ After finding the requested post, Rails uses the +edit.html.erb+ view to display it:
665
+
666
+ <erb>
667
+ <h1>Editing post</h1>
668
+
669
+ <% form_for(@post) do |f| %>
670
+ <%= f.error_messages %>
671
+
672
+ <p>
673
+ <%= f.label :name %><br />
674
+ <%= f.text_field :name %>
675
+ </p>
676
+ <p>
677
+ <%= f.label :title %><br />
678
+ <%= f.text_field :title %>
679
+ </p>
680
+ <p>
681
+ <%= f.label :content %><br />
682
+ <%= f.text_area :content %>
683
+ </p>
684
+ <p>
685
+ <%= f.submit "Update" %>
686
+ </p>
687
+ <% end %>
688
+
689
+ <%= link_to 'Show', @post %> |
690
+ <%= link_to 'Back', posts_path %>
691
+ </erb>
692
+
693
+ Submitting the form created by this view will invoke the +update+ action within the controller:
694
+
695
+ <ruby>
696
+ def update
697
+ @post = Post.find(params[:id])
698
+
699
+ respond_to do |format|
700
+ if @post.update_attributes(params[:post])
701
+ flash[:notice] = 'Post was successfully updated.'
702
+ format.html { redirect_to(@post) }
703
+ format.xml { head :ok }
704
+ else
705
+ format.html { render :action => "edit" }
706
+ format.xml { render :xml => @post.errors,
707
+ :status => :unprocessable_entity }
708
+ end
709
+ end
710
+ end
711
+ </ruby>
712
+
713
+ In the +update+ action, Rails first uses the +:id+ parameter passed back from the edit view to locate the database record that's being edited. The +update_attributes+ call then takes the rest of the parameters from the request and applies them to this record. If all goes well, the user is redirected to the post's +show+ view. If there are any problems, it's back to +edit+ to correct them.
714
+
715
+ NOTE. Sharp-eyed readers will have noticed that the +form_for+ declaration is identical for the +new+ and +edit+ views. Rails generates different code for the two forms because it's smart enough to notice that in the one case it's being passed a new record that has never been saved, and in the other case an existing record that has already been saved to the database. In a production Rails application, you would ordinarily eliminate this duplication by moving identical code to a _partial template_, which you could then include in both parent templates. But the scaffold generator tries not to make too many assumptions, and generates code that's easy to modify if you want different forms for +create+ and +edit+.
716
+
717
+ h4. Destroying a Post
718
+
719
+ Finally, clicking one of the +destroy+ links sends the associated id to the +destroy+ action:
720
+
721
+ <ruby>
722
+ def destroy
723
+ @post = Post.find(params[:id])
724
+ @post.destroy
725
+
726
+ respond_to do |format|
727
+ format.html { redirect_to(posts_url) }
728
+ format.xml { head :ok }
729
+ end
730
+ end
731
+ </ruby>
732
+
733
+ The +destroy+ method of an Active Record model instance removes the corresponding record from the database. After that's done, there isn't any record to display, so Rails redirects the user's browser to the index view for the model.
734
+
735
+ h3. DRYing up the Code
736
+
737
+ At this point, it's worth looking at some of the tools that Rails provides to eliminate duplication in your code. In particular, you can use _partials_ to clean up duplication in views and _filters_ to help with duplication in controllers.
738
+
739
+ h4. Using Partials to Eliminate View Duplication
740
+
741
+ As you saw earlier, the scaffold-generated views for the +new+ and +edit+ actions are largely identical. You can pull the shared code out into a partial template. This requires editing the new and edit views, and adding a new template. The new +_form.html.erb+ template should be saved in the same +app/views/posts+ folder as the files from which it is being extracted. Note that the name of this file begins with an underscore; that's the Rails naming convention for partial templates.
742
+
743
+ <tt>new.html.erb</tt>:
744
+
745
+ <erb>
746
+ <h1>New post</h1>
747
+
748
+ <%= render :partial => "form" %>
749
+
750
+ <%= link_to 'Back', posts_path %>
751
+ </erb>
752
+
753
+ <tt>edit.html.erb</tt>:
754
+
755
+ <erb>
756
+ <h1>Editing post</h1>
757
+
758
+ <%= render :partial => "form" %>
759
+
760
+ <%= link_to 'Show', @post %> |
761
+ <%= link_to 'Back', posts_path %>
762
+ </erb>
763
+
764
+ <tt>_form.html.erb</tt>:
765
+
766
+ <erb>
767
+ <% form_for(@post) do |f| %>
768
+ <%= f.error_messages %>
769
+
770
+ <p>
771
+ <%= f.label :name %><br />
772
+ <%= f.text_field :name %>
773
+ </p>
774
+ <p>
775
+ <%= f.label :title, "title" %><br />
776
+ <%= f.text_field :title %>
777
+ </p>
778
+ <p>
779
+ <%= f.label :content %><br />
780
+ <%= f.text_area :content %>
781
+ </p>
782
+ <p>
783
+ <%= f.submit "Save" %>
784
+ </p>
785
+ <% end %>
786
+ </erb>
787
+
788
+ Now, when Rails renders the +new+ or +edit+ view, it will insert the +_form+ partial at the indicated point. Note the naming convention for partials: if you refer to a partial named +form+ inside of a view, the corresponding file is +_form.html.erb+, with a leading underscore.
789
+
790
+ For more information on partials, refer to the "Layouts and Rendering in Rails":layouts_and_rendering.html#using-partials guide.
791
+
792
+ h4. Using Filters to Eliminate Controller Duplication
793
+
794
+ At this point, if you look at the controller for posts, you'll see some duplication:
795
+
796
+ <ruby>
797
+ class PostsController < ApplicationController
798
+ # ...
799
+ def show
800
+ @post = Post.find(params[:id])
801
+ # ...
802
+ end
803
+
804
+ def edit
805
+ @post = Post.find(params[:id])
806
+ end
807
+
808
+ def update
809
+ @post = Post.find(params[:id])
810
+ # ...
811
+ end
812
+
813
+ def destroy
814
+ @post = Post.find(params[:id])
815
+ # ...
816
+ end
817
+ end
818
+ </ruby>
819
+
820
+ Four instances of the exact same line of code doesn't seem very DRY. Rails provides _filters_ as a way to address this sort of repeated code. In this case, you can DRY things up by using a +before_filter+:
821
+
822
+ <ruby>
823
+ class PostsController < ApplicationController
824
+ before_filter :find_post,
825
+ :only => [:show, :edit, :update, :destroy]
826
+ # ...
827
+ def show
828
+ # ...
829
+ end
830
+
831
+ def edit
832
+ end
833
+
834
+ def update
835
+ # ...
836
+ end
837
+
838
+ def destroy
839
+ # ...
840
+ end
841
+
842
+ private
843
+ def find_post
844
+ @post = Post.find(params[:id])
845
+ end
846
+ end
847
+ </ruby>
848
+
849
+ Rails runs _before filters_ before any action in the controller. You can use the +:only+ clause to limit a before filter to only certain actions, or an +:except+ clause to specifically skip a before filter for certain actions. Rails also allows you to define _after filters_ that run after processing an action, as well as _around filters_ that surround the processing of actions. Filters can also be defined in external classes to make it easy to share them between controllers.
850
+
851
+ For more information on filters, see the "Action Controller Overview":action_controller_overview.html guide.
852
+
853
+ h3. Adding a Second Model
854
+
855
+ Now that you've seen what's in a model built with scaffolding, it's time to add a second model to the application. The second model will handle comments on blog posts.
856
+
857
+ h4. Generating a Model
858
+
859
+ Models in Rails use a singular name, and their corresponding database tables use a plural name. For the model to hold comments, the convention is to use the name Comment. Even if you don't want to use the entire apparatus set up by scaffolding, most Rails developers still use generators to make things like models and controllers. To create the new model, run this command in your terminal:
860
+
861
+ <shell>
862
+ $ script/generate model Comment commenter:string body:text
863
+ post:references
864
+ </shell>
865
+
866
+ This command will generate four files:
867
+
868
+ * +app/models/comment.rb+ - The model
869
+ * +db/migrate/20091013214407_create_comments.rb+ - The migration
870
+ * +test/unit/comment_test.rb+ and +test/fixtures/comments.yml+ - The test harness.
871
+
872
+ First, take a look at +comment.rb+:
873
+
874
+ <ruby>
875
+ class Comment < ActiveRecord::Base
876
+ belongs_to :post
877
+ end
878
+ </ruby>
879
+
880
+ This is very similar to the +post.rb+ model that you saw earlier. The difference is the line +belongs_to :post+, which sets up an Active Record _association_. You'll learn a little about associations in the next section of this guide.
881
+
882
+ In addition to the model, Rails has also made a migration to create the corresponding database table:
883
+
884
+ <ruby>
885
+ class CreateComments < ActiveRecord::Migration
886
+ def self.up
887
+ create_table :comments do |t|
888
+ t.string :commenter
889
+ t.text :body
890
+ t.references :post
891
+
892
+ t.timestamps
893
+ end
894
+ end
895
+
896
+ def self.down
897
+ drop_table :comments
898
+ end
899
+ end
900
+ </ruby>
901
+
902
+ The +t.references+ line sets up a foreign key column for the association between the two models. Go ahead and run the migration:
903
+
904
+ <shell>
905
+ $ rake db:migrate
906
+ </shell>
907
+
908
+ Rails is smart enough to only execute the migrations that have not already been run against the current database.
909
+
910
+ h4. Associating Models
911
+
912
+ Active Record associations let you easily declare the relationship between two models. In the case of comments and posts, you could write out the relationships this way:
913
+
914
+ * Each comment belongs to one post
915
+ * One post can have many comments
916
+
917
+ In fact, this is very close to the syntax that Rails uses to declare this association. You've already seen the line of code inside the Comment model that makes each comment belong to a Post:
918
+
919
+ <ruby>
920
+ class Comment < ActiveRecord::Base
921
+ belongs_to :post
922
+ end
923
+ </ruby>
924
+
925
+ You'll need to edit the +post.rb+ file to add the other side of the association:
926
+
927
+ <ruby>
928
+ class Post < ActiveRecord::Base
929
+ validates_presence_of :name, :title
930
+ validates_length_of :title, :minimum => 5
931
+ has_many :comments
932
+ end
933
+ </ruby>
934
+
935
+ These two declarations enable a good bit of automatic behavior. For example, if you have an instance variable +@post+ containing a post, you can retrieve all the comments belonging to that post as the array +@post.comments+.
936
+
937
+ TIP: For more information on Active Record associations, see the "Active Record Associations":association_basics.html guide.
938
+
939
+ h4. Adding a Route
940
+
941
+ _Routes_ are entries in the +config/routes.rb+ file that tell Rails how to match incoming HTTP requests to controller actions. Open up that file and find the existing line referring to +posts+ (it will be right at the top of the file). Then edit it as follows:
942
+
943
+ <ruby>
944
+ map.resources :posts, :has_many => :comments
945
+ </ruby>
946
+
947
+ This creates +comments+ as a _nested resource_ within +posts+. This is another part of capturing the hierarchical relationship that exists between posts and comments.
948
+
949
+ TIP: For more information on routing, see the "Rails Routing from the Outside In":routing.html guide.
950
+
951
+ h4. Generating a Controller
952
+
953
+ With the model in hand, you can turn your attention to creating a matching controller. Again, there's a generator for this:
954
+
955
+ <shell>
956
+ $ script/generate controller Comments index show new edit
957
+ </shell>
958
+
959
+ This creates eight files:
960
+
961
+ * +app/controllers/comments_controller.rb+ - The controller
962
+ * +app/helpers/comments_helper.rb+ - A view helper file
963
+ * +app/views/comments/index.html.erb+ - The view for the index action
964
+ * +app/views/comments/show.html.erb+ - The view for the show action
965
+ * +app/views/comments/new.html.erb+ - The view for the new action
966
+ * +app/views/comments/edit.html.erb+ - The view for the edit action
967
+ * +test/functional/comments_controller_test.rb+ - The functional tests for the controller
968
+ * +test/unit/helpers/comments_helper_test.rb+ - The unit tests for the helper
969
+
970
+ The controller will be generated with empty methods and views for each action that you specified in the call to +script/generate controller+:
971
+
972
+ <ruby>
973
+ class CommentsController < ApplicationController
974
+ def index
975
+ end
976
+
977
+ def show
978
+ end
979
+
980
+ def new
981
+ end
982
+
983
+ def edit
984
+ end
985
+
986
+ end
987
+ </ruby>
988
+
989
+ You'll need to flesh this out with code to actually process requests appropriately in each method. Here's a version that (for simplicity's sake) only responds to requests that require HTML:
990
+
991
+ <ruby>
992
+ class CommentsController < ApplicationController
993
+ before_filter :find_post
994
+
995
+ def index
996
+ @comments = @post.comments
997
+ end
998
+
999
+ def show
1000
+ @comment = @post.comments.find(params[:id])
1001
+ end
1002
+
1003
+ def new
1004
+ @comment = @post.comments.build
1005
+ end
1006
+
1007
+ def create
1008
+ @comment = @post.comments.build(params[:comment])
1009
+ if @comment.save
1010
+ redirect_to post_comment_url(@post, @comment)
1011
+ else
1012
+ render :action => "new"
1013
+ end
1014
+ end
1015
+
1016
+ def edit
1017
+ @comment = @post.comments.find(params[:id])
1018
+ end
1019
+
1020
+ def update
1021
+ @comment = Comment.find(params[:id])
1022
+ if @comment.update_attributes(params[:comment])
1023
+ redirect_to post_comment_url(@post, @comment)
1024
+ else
1025
+ render :action => "edit"
1026
+ end
1027
+ end
1028
+
1029
+ def destroy
1030
+ @comment = Comment.find(params[:id])
1031
+ @comment.destroy
1032
+ redirect_to post_comments_path(@post)
1033
+ end
1034
+
1035
+ private
1036
+ def find_post
1037
+ @post = Post.find(params[:post_id])
1038
+ end
1039
+
1040
+ end
1041
+ </ruby>
1042
+
1043
+ You'll see a bit more complexity here than you did in the controller for posts. That's a side-effect of the nesting that you've set up; each request for a comment has to keep track of the post to which the comment is attached.
1044
+
1045
+ In addition, the code takes advantage of some of the methods available for an association. For example, in the +new+ method, it calls
1046
+
1047
+ <ruby>
1048
+ @comment = @post.comments.build
1049
+ </ruby>
1050
+
1051
+ This creates a new +Comment+ object _and_ sets up the +post_id+ field to have the +id+ from the specified +Post+ object in a single operation.
1052
+
1053
+ h4. Building Views
1054
+
1055
+ Because you skipped scaffolding, you'll need to build views for comments "by hand". Invoking +script/generate controller+ will give you skeleton views, but they'll be devoid of actual content. Here's a first pass at fleshing out the comment views.
1056
+
1057
+ The +views/comments/index.html.erb+ view:
1058
+
1059
+ <erb>
1060
+ <h1>Comments for <%= @post.title %></h1>
1061
+
1062
+ <table>
1063
+ <tr>
1064
+ <th>Commenter</th>
1065
+ <th>Body</th>
1066
+ </tr>
1067
+
1068
+ <% for comment in @comments %>
1069
+ <tr>
1070
+ <td><%=h comment.commenter %></td>
1071
+ <td><%=h comment.body %></td>
1072
+ <td><%= link_to 'Show', post_comment_path(@post, comment) %></td>
1073
+ <td>
1074
+ <%= link_to 'Edit', edit_post_comment_path(@post, comment) %>
1075
+ </td>
1076
+ <td>
1077
+ <%= link_to 'Destroy', post_comment_path(@post, comment),
1078
+ :confirm => 'Are you sure?', :method => :delete %>
1079
+ </td>
1080
+ </tr>
1081
+ <% end %>
1082
+ </table>
1083
+
1084
+ <br />
1085
+
1086
+ <%= link_to 'New comment', new_post_comment_path(@post) %>
1087
+ <%= link_to 'Back to Post', @post %>
1088
+ </erb>
1089
+
1090
+ The +views/comments/new.html.erb+ view:
1091
+
1092
+ <erb>
1093
+ <h1>New comment</h1>
1094
+
1095
+ <% form_for([@post, @comment]) do |f| %>
1096
+ <%= f.error_messages %>
1097
+
1098
+ <p>
1099
+ <%= f.label :commenter %><br />
1100
+ <%= f.text_field :commenter %>
1101
+ </p>
1102
+ <p>
1103
+ <%= f.label :body %><br />
1104
+ <%= f.text_area :body %>
1105
+ </p>
1106
+ <p>
1107
+ <%= f.submit "Create" %>
1108
+ </p>
1109
+ <% end %>
1110
+
1111
+ <%= link_to 'Back', post_comments_path(@post) %>
1112
+ </erb>
1113
+
1114
+ The +views/comments/show.html.erb+ view:
1115
+
1116
+ <erb>
1117
+ <h1>Comment on <%= @post.title %></h1>
1118
+
1119
+ <p>
1120
+ <b>Commenter:</b>
1121
+ <%=h @comment.commenter %>
1122
+ </p>
1123
+
1124
+ <p>
1125
+ <b>Comment:</b>
1126
+ <%=h @comment.body %>
1127
+ </p>
1128
+
1129
+ <%= link_to 'Edit', edit_post_comment_path(@post, @comment) %> |
1130
+ <%= link_to 'Back', post_comments_path(@post) %>
1131
+ </erb>
1132
+
1133
+ The +views/comments/edit.html.erb+ view:
1134
+
1135
+ <erb>
1136
+ <h1>Editing comment</h1>
1137
+
1138
+ <% form_for([@post, @comment]) do |f| %>
1139
+ <%= f.error_messages %>
1140
+
1141
+ <p>
1142
+ <%= f.label :commenter %><br />
1143
+ <%= f.text_field :commenter %>
1144
+ </p>
1145
+ <p>
1146
+ <%= f.label :body %><br />
1147
+ <%= f.text_area :body %>
1148
+ </p>
1149
+ <p>
1150
+ <%= f.submit "Update" %>
1151
+ </p>
1152
+ <% end %>
1153
+
1154
+ <%= link_to 'Show', post_comment_path(@post, @comment) %> |
1155
+ <%= link_to 'Back', post_comments_path(@post) %>
1156
+ </erb>
1157
+
1158
+ Again, the added complexity here (compared to the views you saw for managing posts) comes from the necessity of juggling a post and its comments at the same time.
1159
+
1160
+ h4. Hooking Comments to Posts
1161
+
1162
+ As a next step, I'll modify the +views/posts/show.html.erb+ view to show the comments on that post, and to allow managing those comments:
1163
+
1164
+ <erb>
1165
+ <p>
1166
+ <b>Name:</b>
1167
+ <%=h @post.name %>
1168
+ </p>
1169
+
1170
+ <p>
1171
+ <b>Title:</b>
1172
+ <%=h @post.title %>
1173
+ </p>
1174
+
1175
+ <p>
1176
+ <b>Content:</b>
1177
+ <%=h @post.content %>
1178
+ </p>
1179
+
1180
+ <h2>Comments</h2>
1181
+ <% @post.comments.each do |c| %>
1182
+ <p>
1183
+ <b>Commenter:</b>
1184
+ <%=h c.commenter %>
1185
+ </p>
1186
+
1187
+ <p>
1188
+ <b>Comment:</b>
1189
+ <%=h c.body %>
1190
+ </p>
1191
+ <% end %>
1192
+
1193
+ <%= link_to 'Edit Post', edit_post_path(@post) %> |
1194
+ <%= link_to 'Back to Posts', posts_path %> |
1195
+ <%= link_to 'Manage Comments', post_comments_path(@post) %>
1196
+ </erb>
1197
+
1198
+ Note that each post has its own individual comments collection, accessible as +@post.comments+. That's a consequence of the declarative associations in the models. Path helpers such as +post_comments_path+ come from the nested route declaration in +config/routes.rb+.
1199
+
1200
+ h4. Deleting Associated Objects
1201
+
1202
+ If you decide at some point to delete a post, you likely want to delete the comments associated with that post as well. You can do so by taking advantage of the association option +dependent+. All you need to do is modify the +post.rb+ as follows:
1203
+
1204
+ <ruby>
1205
+ class Post < ActiveRecord::Base
1206
+ validates_presence_of :name, :title
1207
+ validates_length_of :title, :minimum => 5
1208
+ has_many :comments, :dependent => :destroy
1209
+ end
1210
+ </ruby>
1211
+
1212
+ h3. Building a Multi-Model Form
1213
+
1214
+ Comments and posts are edited on two separate forms - which makes sense, given the flow of this mini-application. But what if you want to edit more than one thing on a single form? Rails 2.3 offers new support for nested forms. Let's add support for giving each post multiple tags, right in the form where you create the post. First, create a new model to hold the tags:
1215
+
1216
+ <shell>
1217
+ $ script/generate model tag name:string post:references
1218
+ </shell>
1219
+
1220
+ Run the migration to create the database table:
1221
+
1222
+ <shell>
1223
+ $ rake db:migrate
1224
+ </shell>
1225
+
1226
+ Next, edit the +post.rb+ file to create the other side of the association, and to tell Rails (via the +accepts_nested_attributes+ macro) that you intend to edit tags via posts:
1227
+
1228
+ <ruby>
1229
+ class Post < ActiveRecord::Base
1230
+ validates_presence_of :name, :title
1231
+ validates_length_of :title, :minimum => 5
1232
+ has_many :comments
1233
+ has_many :tags
1234
+
1235
+ accepts_nested_attributes_for :tags, :allow_destroy => :true,
1236
+ :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
1237
+ end
1238
+ </ruby>
1239
+
1240
+ The +:allow_destroy+ option on the nested attribute declaration tells Rails to display a "remove" checkbox on the view that you'll build shortly. The +:reject_if+ option prevents saving new tags that do not have any attributes filled in.
1241
+
1242
+ You'll also need to modify +views/posts/_form.html.erb+ to include the tags:
1243
+
1244
+ <erb>
1245
+ <% @post.tags.build if @post.tags.empty? %>
1246
+ <% form_for(@post) do |post_form| %>
1247
+ <%= post_form.error_messages %>
1248
+
1249
+ <p>
1250
+ <%= post_form.label :name %><br />
1251
+ <%= post_form.text_field :name %>
1252
+ </p>
1253
+ <p>
1254
+ <%= post_form.label :title, "Title" %><br />
1255
+ <%= post_form.text_field :title %>
1256
+ </p>
1257
+ <p>
1258
+ <%= post_form.label :content %><br />
1259
+ <%= post_form.text_area :content %>
1260
+ </p>
1261
+ <h2>Tags</h2>
1262
+ <% post_form.fields_for :tags do |tag_form| %>
1263
+ <p>
1264
+ <%= tag_form.label :name, 'Tag:' %>
1265
+ <%= tag_form.text_field :name %>
1266
+ </p>
1267
+ <% unless tag_form.object.nil? || tag_form.object.new_record? %>
1268
+ <p>
1269
+ <%= tag_form.label :_delete, 'Remove:' %>
1270
+ <%= tag_form.check_box :_delete %>
1271
+ </p>
1272
+ <% end %>
1273
+ <% end %>
1274
+
1275
+ <p>
1276
+ <%= post_form.submit "Save" %>
1277
+ </p>
1278
+ <% end %>
1279
+ </erb>
1280
+
1281
+ With these changes in place, you'll find that you can edit a post and its tags directly on the same view.
1282
+
1283
+ NOTE. You may want to use JavaScript to dynamically add additional tags on a single form. For an example of this and other advanced techniques, see the "complex form examples application":http://github.com/alloy/complex-form-examples/tree/master.
1284
+
1285
+ h3. What's Next?
1286
+
1287
+ Now that you've seen your first Rails application, you should feel free to update it and experiment on your own. But you don't have to do everything without help. As you need assistance getting up and running with Rails, feel free to consult these support resources:
1288
+
1289
+ * The "Ruby On Rails guides":http://guides.rubyonrails.org
1290
+ * The "Ruby on Rails mailing list":http://groups.google.com/group/rubyonrails-talk
1291
+ * The "#rubyonrails":irc://irc.freenode.net/#rubyonrails channel on irc.freenode.net
1292
+ * The "Rails Wiki":http://wiki.rubyonrails.org/
1293
+
1294
+ Rails also comes with built-in help that you can generate using the rake command-line utility:
1295
+
1296
+ * Running +rake doc:guides+ will put a full copy of the Rails Guides in the +doc/guides+ folder of your application. Open +doc/guides/index.html+ in your web browser to explore the Guides.
1297
+ * Running +rake doc:rails+ will put a full copy of the API documentation for Rails in the +doc/api+ folder of your application. Open +doc/api/index.html+ in your web browser to explore the API documentation.
1298
+
1299
+ h3. Changelog
1300
+
1301
+ "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/2
1302
+
1303
+ * July 18, 2009: Minor cleanup in anticipation of Rails 2.3.3 by "Mike Gunderloy":credits.html#mgunderloy
1304
+ * February 1, 2009: Updated for Rails 2.3 by "Mike Gunderloy":credits.html#mgunderloy
1305
+ * November 3, 2008: Formatting patch from Dave Rothlisberger
1306
+ * November 1, 2008: First approved version by "Mike Gunderloy":credits.html#mgunderloy
1307
+ * October 16, 2008: Revised based on feedback from Pratik Naik by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
1308
+ * October 13, 2008: First complete draft by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
1309
+ * October 12, 2008: More detail, rearrangement, editing by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
1310
+ * September 8, 2008: initial version by James Miller (not yet approved for publication)