rails 4.1.0 → 5.2.0

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

Potentially problematic release.


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

Files changed (284) hide show
  1. checksums.yaml +5 -5
  2. data/README.md +33 -19
  3. metadata +65 -310
  4. data/guides/CHANGELOG.md +0 -13
  5. data/guides/Rakefile +0 -77
  6. data/guides/assets/images/akshaysurve.jpg +0 -0
  7. data/guides/assets/images/belongs_to.png +0 -0
  8. data/guides/assets/images/book_icon.gif +0 -0
  9. data/guides/assets/images/bullet.gif +0 -0
  10. data/guides/assets/images/chapters_icon.gif +0 -0
  11. data/guides/assets/images/check_bullet.gif +0 -0
  12. data/guides/assets/images/credits_pic_blank.gif +0 -0
  13. data/guides/assets/images/csrf.png +0 -0
  14. data/guides/assets/images/edge_badge.png +0 -0
  15. data/guides/assets/images/favicon.ico +0 -0
  16. data/guides/assets/images/feature_tile.gif +0 -0
  17. data/guides/assets/images/footer_tile.gif +0 -0
  18. data/guides/assets/images/fxn.png +0 -0
  19. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  20. data/guides/assets/images/getting_started/challenge.png +0 -0
  21. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  22. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  23. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  24. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  25. data/guides/assets/images/getting_started/new_article.png +0 -0
  26. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  27. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  28. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  29. data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
  30. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  31. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  32. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  33. data/guides/assets/images/grey_bullet.gif +0 -0
  34. data/guides/assets/images/habtm.png +0 -0
  35. data/guides/assets/images/has_many.png +0 -0
  36. data/guides/assets/images/has_many_through.png +0 -0
  37. data/guides/assets/images/has_one.png +0 -0
  38. data/guides/assets/images/has_one_through.png +0 -0
  39. data/guides/assets/images/header_backdrop.png +0 -0
  40. data/guides/assets/images/header_tile.gif +0 -0
  41. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  42. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  43. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  44. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  45. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  46. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  47. data/guides/assets/images/icons/README +0 -5
  48. data/guides/assets/images/icons/callouts/1.png +0 -0
  49. data/guides/assets/images/icons/callouts/10.png +0 -0
  50. data/guides/assets/images/icons/callouts/11.png +0 -0
  51. data/guides/assets/images/icons/callouts/12.png +0 -0
  52. data/guides/assets/images/icons/callouts/13.png +0 -0
  53. data/guides/assets/images/icons/callouts/14.png +0 -0
  54. data/guides/assets/images/icons/callouts/15.png +0 -0
  55. data/guides/assets/images/icons/callouts/2.png +0 -0
  56. data/guides/assets/images/icons/callouts/3.png +0 -0
  57. data/guides/assets/images/icons/callouts/4.png +0 -0
  58. data/guides/assets/images/icons/callouts/5.png +0 -0
  59. data/guides/assets/images/icons/callouts/6.png +0 -0
  60. data/guides/assets/images/icons/callouts/7.png +0 -0
  61. data/guides/assets/images/icons/callouts/8.png +0 -0
  62. data/guides/assets/images/icons/callouts/9.png +0 -0
  63. data/guides/assets/images/icons/caution.png +0 -0
  64. data/guides/assets/images/icons/example.png +0 -0
  65. data/guides/assets/images/icons/home.png +0 -0
  66. data/guides/assets/images/icons/important.png +0 -0
  67. data/guides/assets/images/icons/next.png +0 -0
  68. data/guides/assets/images/icons/note.png +0 -0
  69. data/guides/assets/images/icons/prev.png +0 -0
  70. data/guides/assets/images/icons/tip.png +0 -0
  71. data/guides/assets/images/icons/up.png +0 -0
  72. data/guides/assets/images/icons/warning.png +0 -0
  73. data/guides/assets/images/nav_arrow.gif +0 -0
  74. data/guides/assets/images/oscardelben.jpg +0 -0
  75. data/guides/assets/images/polymorphic.png +0 -0
  76. data/guides/assets/images/radar.png +0 -0
  77. data/guides/assets/images/rails4_features.png +0 -0
  78. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  79. data/guides/assets/images/rails_guides_logo.gif +0 -0
  80. data/guides/assets/images/rails_logo_remix.gif +0 -0
  81. data/guides/assets/images/session_fixation.png +0 -0
  82. data/guides/assets/images/tab_grey.gif +0 -0
  83. data/guides/assets/images/tab_info.gif +0 -0
  84. data/guides/assets/images/tab_note.gif +0 -0
  85. data/guides/assets/images/tab_red.gif +0 -0
  86. data/guides/assets/images/tab_yellow.gif +0 -0
  87. data/guides/assets/images/tab_yellow.png +0 -0
  88. data/guides/assets/images/vijaydev.jpg +0 -0
  89. data/guides/assets/javascripts/guides.js +0 -53
  90. data/guides/assets/javascripts/jquery.min.js +0 -4
  91. data/guides/assets/javascripts/responsive-tables.js +0 -43
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  116. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  117. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
  118. data/guides/assets/stylesheets/fixes.css +0 -16
  119. data/guides/assets/stylesheets/kindle.css +0 -11
  120. data/guides/assets/stylesheets/main.css +0 -710
  121. data/guides/assets/stylesheets/print.css +0 -52
  122. data/guides/assets/stylesheets/reset.css +0 -43
  123. data/guides/assets/stylesheets/responsive-tables.css +0 -50
  124. data/guides/assets/stylesheets/style.css +0 -13
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  133. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  142. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  143. data/guides/bug_report_templates/action_controller_gem.rb +0 -47
  144. data/guides/bug_report_templates/action_controller_master.rb +0 -53
  145. data/guides/bug_report_templates/active_record_gem.rb +0 -40
  146. data/guides/bug_report_templates/active_record_master.rb +0 -49
  147. data/guides/code/getting_started/Gemfile +0 -40
  148. data/guides/code/getting_started/Gemfile.lock +0 -126
  149. data/guides/code/getting_started/README.rdoc +0 -28
  150. data/guides/code/getting_started/Rakefile +0 -6
  151. data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
  152. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
  153. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
  154. data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +0 -3
  155. data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
  156. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
  157. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
  158. data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +0 -3
  159. data/guides/code/getting_started/app/controllers/application_controller.rb +0 -5
  160. data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -23
  161. data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -53
  162. data/guides/code/getting_started/app/controllers/welcome_controller.rb +0 -4
  163. data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
  164. data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
  165. data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -2
  166. data/guides/code/getting_started/app/helpers/welcome_helper.rb +0 -2
  167. data/guides/code/getting_started/app/models/comment.rb +0 -3
  168. data/guides/code/getting_started/app/models/post.rb +0 -7
  169. data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
  170. data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
  171. data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
  172. data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -27
  173. data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -5
  174. data/guides/code/getting_started/app/views/posts/index.html.erb +0 -21
  175. data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
  176. data/guides/code/getting_started/app/views/posts/show.html.erb +0 -18
  177. data/guides/code/getting_started/app/views/welcome/index.html.erb +0 -4
  178. data/guides/code/getting_started/bin/bundle +0 -4
  179. data/guides/code/getting_started/bin/rails +0 -4
  180. data/guides/code/getting_started/bin/rake +0 -4
  181. data/guides/code/getting_started/config.ru +0 -4
  182. data/guides/code/getting_started/config/application.rb +0 -18
  183. data/guides/code/getting_started/config/boot.rb +0 -4
  184. data/guides/code/getting_started/config/database.yml +0 -25
  185. data/guides/code/getting_started/config/environment.rb +0 -5
  186. data/guides/code/getting_started/config/environments/development.rb +0 -30
  187. data/guides/code/getting_started/config/environments/production.rb +0 -80
  188. data/guides/code/getting_started/config/environments/test.rb +0 -36
  189. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
  190. data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
  191. data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
  192. data/guides/code/getting_started/config/initializers/locale.rb +0 -9
  193. data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
  194. data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
  195. data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
  196. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
  197. data/guides/code/getting_started/config/locales/en.yml +0 -23
  198. data/guides/code/getting_started/config/routes.rb +0 -7
  199. data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +0 -10
  200. data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +0 -11
  201. data/guides/code/getting_started/db/schema.rb +0 -33
  202. data/guides/code/getting_started/db/seeds.rb +0 -7
  203. data/guides/code/getting_started/public/404.html +0 -60
  204. data/guides/code/getting_started/public/422.html +0 -60
  205. data/guides/code/getting_started/public/500.html +0 -59
  206. data/guides/code/getting_started/public/favicon.ico +0 -0
  207. data/guides/code/getting_started/public/robots.txt +0 -5
  208. data/guides/code/getting_started/test/controllers/comments_controller_test.rb +0 -7
  209. data/guides/code/getting_started/test/controllers/posts_controller_test.rb +0 -7
  210. data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +0 -9
  211. data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
  212. data/guides/code/getting_started/test/fixtures/posts.yml +0 -9
  213. data/guides/code/getting_started/test/helpers/comments_helper_test.rb +0 -4
  214. data/guides/code/getting_started/test/helpers/posts_helper_test.rb +0 -4
  215. data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +0 -4
  216. data/guides/code/getting_started/test/models/comment_test.rb +0 -7
  217. data/guides/code/getting_started/test/models/post_test.rb +0 -7
  218. data/guides/code/getting_started/test/test_helper.rb +0 -15
  219. data/guides/rails_guides.rb +0 -63
  220. data/guides/rails_guides/generator.rb +0 -248
  221. data/guides/rails_guides/helpers.rb +0 -53
  222. data/guides/rails_guides/indexer.rb +0 -68
  223. data/guides/rails_guides/kindle.rb +0 -119
  224. data/guides/rails_guides/levenshtein.rb +0 -31
  225. data/guides/rails_guides/markdown.rb +0 -163
  226. data/guides/rails_guides/markdown/renderer.rb +0 -82
  227. data/guides/source/2_2_release_notes.md +0 -435
  228. data/guides/source/2_3_release_notes.md +0 -621
  229. data/guides/source/3_0_release_notes.md +0 -611
  230. data/guides/source/3_1_release_notes.md +0 -556
  231. data/guides/source/3_2_release_notes.md +0 -565
  232. data/guides/source/4_0_release_notes.md +0 -276
  233. data/guides/source/4_1_release_notes.md +0 -731
  234. data/guides/source/_license.html.erb +0 -2
  235. data/guides/source/_welcome.html.erb +0 -22
  236. data/guides/source/action_controller_overview.md +0 -1175
  237. data/guides/source/action_mailer_basics.md +0 -689
  238. data/guides/source/action_view_overview.md +0 -1610
  239. data/guides/source/active_model_basics.md +0 -200
  240. data/guides/source/active_record_basics.md +0 -373
  241. data/guides/source/active_record_callbacks.md +0 -410
  242. data/guides/source/active_record_querying.md +0 -1771
  243. data/guides/source/active_record_validations.md +0 -1169
  244. data/guides/source/active_support_core_extensions.md +0 -3864
  245. data/guides/source/active_support_instrumentation.md +0 -496
  246. data/guides/source/api_documentation_guidelines.md +0 -281
  247. data/guides/source/asset_pipeline.md +0 -1163
  248. data/guides/source/association_basics.md +0 -2229
  249. data/guides/source/caching_with_rails.md +0 -354
  250. data/guides/source/command_line.md +0 -603
  251. data/guides/source/configuring.md +0 -942
  252. data/guides/source/contributing_to_ruby_on_rails.md +0 -544
  253. data/guides/source/credits.html.erb +0 -80
  254. data/guides/source/debugging_rails_applications.md +0 -707
  255. data/guides/source/development_dependencies_install.md +0 -278
  256. data/guides/source/documents.yaml +0 -194
  257. data/guides/source/engines.md +0 -1391
  258. data/guides/source/form_helpers.md +0 -1001
  259. data/guides/source/generators.md +0 -663
  260. data/guides/source/getting_started.md +0 -1947
  261. data/guides/source/i18n.md +0 -1043
  262. data/guides/source/index.html.erb +0 -27
  263. data/guides/source/initialization.md +0 -657
  264. data/guides/source/kindle/copyright.html.erb +0 -1
  265. data/guides/source/kindle/layout.html.erb +0 -27
  266. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  267. data/guides/source/kindle/toc.html.erb +0 -24
  268. data/guides/source/kindle/toc.ncx.erb +0 -64
  269. data/guides/source/kindle/welcome.html.erb +0 -5
  270. data/guides/source/layout.html.erb +0 -146
  271. data/guides/source/layouts_and_rendering.md +0 -1226
  272. data/guides/source/maintenance_policy.md +0 -56
  273. data/guides/source/migrations.md +0 -1108
  274. data/guides/source/nested_model_forms.md +0 -225
  275. data/guides/source/plugins.md +0 -444
  276. data/guides/source/rails_application_templates.md +0 -248
  277. data/guides/source/rails_on_rack.md +0 -333
  278. data/guides/source/routing.md +0 -1115
  279. data/guides/source/ruby_on_rails_guides_guidelines.md +0 -128
  280. data/guides/source/security.md +0 -1018
  281. data/guides/source/testing.md +0 -1057
  282. data/guides/source/upgrading_ruby_on_rails.md +0 -890
  283. data/guides/source/working_with_javascript_in_rails.md +0 -405
  284. data/guides/w3c_validator.rb +0 -95
@@ -1,56 +0,0 @@
1
- Maintenance Policy for Ruby on Rails
2
- ====================================
3
-
4
- Support of the Rails framework is divided into four groups: New features, bug
5
- fixes, security issues, and severe security issues. They are handled as
6
- follows, all versions in x.y.z format
7
-
8
- --------------------------------------------------------------------------------
9
-
10
- New Features
11
- ------------
12
-
13
- New features are only added to the master branch and will not be made available
14
- in point releases.
15
-
16
- Bug Fixes
17
- ---------
18
-
19
- Only the latest release series will receive bug fixes. When enough bugs are
20
- fixed and its deemed worthy to release a new gem, this is the branch it happens
21
- from.
22
-
23
- **Currently included series:** 4.0.z
24
-
25
- Security Issues
26
- ---------------
27
-
28
- The current release series and the next most recent one will receive patches
29
- and new versions in case of a security issue.
30
-
31
- These releases are created by taking the last released version, applying the
32
- security patches, and releasing. Those patches are then applied to the end of
33
- the x-y-stable branch. For example, a theoretical 1.2.3 security release would
34
- be built from 1.2.2, and then added to the end of 1-2-stable. This means that
35
- security releases are easy to upgrade to if you're running the latest version
36
- of Rails.
37
-
38
- **Currently included series:** 4.0.z, 3.2.z
39
-
40
- Severe Security Issues
41
- ----------------------
42
-
43
- For severe security issues we will provide new versions as above, and also the
44
- last major release series will receive patches and new versions. The
45
- classification of the security issue is judged by the core team.
46
-
47
- **Currently included series:** 4.0.z, 3.2.z
48
-
49
- Unsupported Release Series
50
- --------------------------
51
-
52
- When a release series is no longer supported, it's your own responsibility to
53
- deal with bugs and security issues. We may provide backports of the fixes and
54
- publish them to git, however there will be no new versions released. If you are
55
- not comfortable maintaining your own versions, you should upgrade to a
56
- supported version.
@@ -1,1108 +0,0 @@
1
- Active Record Migrations
2
- ========================
3
-
4
- Migrations are a feature of Active Record that allows you to evolve your
5
- database schema over time. Rather than write schema modifications in pure SQL,
6
- migrations allow you to use an easy Ruby DSL to describe changes to your
7
- tables.
8
-
9
- After reading this guide, you will know:
10
-
11
- * The generators you can use to create them.
12
- * The methods Active Record provides to manipulate your database.
13
- * The Rake tasks that manipulate migrations and your schema.
14
- * How migrations relate to `schema.rb`.
15
-
16
- --------------------------------------------------------------------------------
17
-
18
- Migration Overview
19
- ------------------
20
-
21
- Migrations are a convenient way to alter your database schema over time in a
22
- consistent and easy way. They use a Ruby DSL so that you don't have to write
23
- SQL by hand, allowing your schema and changes to be database independent.
24
-
25
- You can think of each migration as being a new 'version' of the database. A
26
- schema starts off with nothing in it, and each migration modifies it to add or
27
- remove tables, columns, or entries. Active Record knows how to update your
28
- schema along this timeline, bringing it from whatever point it is in the
29
- history to the latest version. Active Record will also update your
30
- `db/schema.rb` file to match the up-to-date structure of your database.
31
-
32
- Here's an example of a migration:
33
-
34
- ```ruby
35
- class CreateProducts < ActiveRecord::Migration
36
- def change
37
- create_table :products do |t|
38
- t.string :name
39
- t.text :description
40
-
41
- t.timestamps
42
- end
43
- end
44
- end
45
- ```
46
-
47
- This migration adds a table called `products` with a string column called
48
- `name` and a text column called `description`. A primary key column called `id`
49
- will also be added implicitly, as it's the default primary key for all Active
50
- Record models. The `timestamps` macro adds two columns, `created_at` and
51
- `updated_at`. These special columns are automatically managed by Active Record
52
- if they exist.
53
-
54
- Note that we define the change that we want to happen moving forward in time.
55
- Before this migration is run, there will be no table. After, the table will
56
- exist. Active Record knows how to reverse this migration as well: if we roll
57
- this migration back, it will remove the table.
58
-
59
- On databases that support transactions with statements that change the schema,
60
- migrations are wrapped in a transaction. If the database does not support this
61
- then when a migration fails the parts of it that succeeded will not be rolled
62
- back. You will have to rollback the changes that were made by hand.
63
-
64
- NOTE: There are certain queries that can't run inside a transaction. If your
65
- adapter supports DDL transactions you can use `disable_ddl_transaction!` to
66
- disable them for a single migration.
67
-
68
- If you wish for a migration to do something that Active Record doesn't know how
69
- to reverse, you can use `reversible`:
70
-
71
- ```ruby
72
- class ChangeProductsPrice < ActiveRecord::Migration
73
- def change
74
- reversible do |dir|
75
- change_table :products do |t|
76
- dir.up { t.change :price, :string }
77
- dir.down { t.change :price, :integer }
78
- end
79
- end
80
- end
81
- end
82
- ```
83
-
84
- Alternatively, you can use `up` and `down` instead of `change`:
85
-
86
- ```ruby
87
- class ChangeProductsPrice < ActiveRecord::Migration
88
- def up
89
- change_table :products do |t|
90
- t.change :price, :string
91
- end
92
- end
93
-
94
- def down
95
- change_table :products do |t|
96
- t.change :price, :integer
97
- end
98
- end
99
- end
100
- ```
101
-
102
- Creating a Migration
103
- --------------------
104
-
105
- ### Creating a Standalone Migration
106
-
107
- Migrations are stored as files in the `db/migrate` directory, one for each
108
- migration class. The name of the file is of the form
109
- `YYYYMMDDHHMMSS_create_products.rb`, that is to say a UTC timestamp
110
- identifying the migration followed by an underscore followed by the name
111
- of the migration. The name of the migration class (CamelCased version)
112
- should match the latter part of the file name. For example
113
- `20080906120000_create_products.rb` should define class `CreateProducts` and
114
- `20080906120001_add_details_to_products.rb` should define
115
- `AddDetailsToProducts`. Rails uses this timestamp to determine which migration
116
- should be run and in what order, so if you're copying a migration from another
117
- application or generate a file yourself, be aware of its position in the order.
118
-
119
- Of course, calculating timestamps is no fun, so Active Record provides a
120
- generator to handle making it for you:
121
-
122
- ```bash
123
- $ rails generate migration AddPartNumberToProducts
124
- ```
125
-
126
- This will create an empty but appropriately named migration:
127
-
128
- ```ruby
129
- class AddPartNumberToProducts < ActiveRecord::Migration
130
- def change
131
- end
132
- end
133
- ```
134
-
135
- If the migration name is of the form "AddXXXToYYY" or "RemoveXXXFromYYY" and is
136
- followed by a list of column names and types then a migration containing the
137
- appropriate `add_column` and `remove_column` statements will be created.
138
-
139
- ```bash
140
- $ rails generate migration AddPartNumberToProducts part_number:string
141
- ```
142
-
143
- will generate
144
-
145
- ```ruby
146
- class AddPartNumberToProducts < ActiveRecord::Migration
147
- def change
148
- add_column :products, :part_number, :string
149
- end
150
- end
151
- ```
152
-
153
- If you'd like to add an index on the new column, you can do that as well:
154
-
155
- ```bash
156
- $ rails generate migration AddPartNumberToProducts part_number:string:index
157
- ```
158
-
159
- will generate
160
-
161
- ```ruby
162
- class AddPartNumberToProducts < ActiveRecord::Migration
163
- def change
164
- add_column :products, :part_number, :string
165
- add_index :products, :part_number
166
- end
167
- end
168
- ```
169
-
170
-
171
- Similarly, you can generate a migration to remove a column from the command line:
172
-
173
- ```bash
174
- $ rails generate migration RemovePartNumberFromProducts part_number:string
175
- ```
176
-
177
- generates
178
-
179
- ```ruby
180
- class RemovePartNumberFromProducts < ActiveRecord::Migration
181
- def change
182
- remove_column :products, :part_number, :string
183
- end
184
- end
185
- ```
186
-
187
- You are not limited to one magically generated column. For example:
188
-
189
- ```bash
190
- $ rails generate migration AddDetailsToProducts part_number:string price:decimal
191
- ```
192
-
193
- generates
194
-
195
- ```ruby
196
- class AddDetailsToProducts < ActiveRecord::Migration
197
- def change
198
- add_column :products, :part_number, :string
199
- add_column :products, :price, :decimal
200
- end
201
- end
202
- ```
203
-
204
- If the migration name is of the form "CreateXXX" and is
205
- followed by a list of column names and types then a migration creating the table
206
- XXX with the columns listed will be generated. For example:
207
-
208
- ```bash
209
- $ rails generate migration CreateProducts name:string part_number:string
210
- ```
211
-
212
- generates
213
-
214
- ```ruby
215
- class CreateProducts < ActiveRecord::Migration
216
- def change
217
- create_table :products do |t|
218
- t.string :name
219
- t.string :part_number
220
- end
221
- end
222
- end
223
- ```
224
-
225
- As always, what has been generated for you is just a starting point. You can add
226
- or remove from it as you see fit by editing the
227
- `db/migrate/YYYYMMDDHHMMSS_add_details_to_products.rb` file.
228
-
229
- Also, the generator accepts column type as `references`(also available as
230
- `belongs_to`). For instance:
231
-
232
- ```bash
233
- $ rails generate migration AddUserRefToProducts user:references
234
- ```
235
-
236
- generates
237
-
238
- ```ruby
239
- class AddUserRefToProducts < ActiveRecord::Migration
240
- def change
241
- add_reference :products, :user, index: true
242
- end
243
- end
244
- ```
245
-
246
- This migration will create a `user_id` column and appropriate index.
247
-
248
- There is also a generator which will produce join tables if `JoinTable` is part of the name:
249
-
250
- ```bash
251
- rails g migration CreateJoinTableCustomerProduct customer product
252
- ```
253
-
254
- will produce the following migration:
255
-
256
- ```ruby
257
- class CreateJoinTableCustomerProduct < ActiveRecord::Migration
258
- def change
259
- create_join_table :customers, :products do |t|
260
- # t.index [:customer_id, :product_id]
261
- # t.index [:product_id, :customer_id]
262
- end
263
- end
264
- end
265
- ```
266
-
267
- ### Model Generators
268
-
269
- The model and scaffold generators will create migrations appropriate for adding
270
- a new model. This migration will already contain instructions for creating the
271
- relevant table. If you tell Rails what columns you want, then statements for
272
- adding these columns will also be created. For example, running:
273
-
274
- ```bash
275
- $ rails generate model Product name:string description:text
276
- ```
277
-
278
- will create a migration that looks like this
279
-
280
- ```ruby
281
- class CreateProducts < ActiveRecord::Migration
282
- def change
283
- create_table :products do |t|
284
- t.string :name
285
- t.text :description
286
-
287
- t.timestamps
288
- end
289
- end
290
- end
291
- ```
292
-
293
- You can append as many column name/type pairs as you want.
294
-
295
- ### Supported Type Modifiers
296
-
297
- You can also specify some options just after the field type between curly
298
- braces. You can use the following modifiers:
299
-
300
- * `limit` Sets the maximum size of the `string/text/binary/integer` fields.
301
- * `precision` Defines the precision for the `decimal` fields, representing the total number of digits in the number.
302
- * `scale` Defines the scale for the `decimal` fields, representing the number of digits after the decimal point.
303
- * `polymorphic` Adds a `type` column for `belongs_to` associations.
304
- * `null` Allows or disallows `NULL` values in the column.
305
-
306
- For instance, running:
307
-
308
- ```bash
309
- $ rails generate migration AddDetailsToProducts 'price:decimal{5,2}' supplier:references{polymorphic}
310
- ```
311
-
312
- will produce a migration that looks like this
313
-
314
- ```ruby
315
- class AddDetailsToProducts < ActiveRecord::Migration
316
- def change
317
- add_column :products, :price, :decimal, precision: 5, scale: 2
318
- add_reference :products, :supplier, polymorphic: true, index: true
319
- end
320
- end
321
- ```
322
-
323
- Writing a Migration
324
- -------------------
325
-
326
- Once you have created your migration using one of the generators it's time to
327
- get to work!
328
-
329
- ### Creating a Table
330
-
331
- The `create_table` method is one of the most fundamental, but most of the time,
332
- will be generated for you from using a model or scaffold generator. A typical
333
- use would be
334
-
335
- ```ruby
336
- create_table :products do |t|
337
- t.string :name
338
- end
339
- ```
340
-
341
- which creates a `products` table with a column called `name` (and as discussed
342
- below, an implicit `id` column).
343
-
344
- By default, `create_table` will create a primary key called `id`. You can change
345
- the name of the primary key with the `:primary_key` option (don't forget to
346
- update the corresponding model) or, if you don't want a primary key at all, you
347
- can pass the option `id: false`. If you need to pass database specific options
348
- you can place an SQL fragment in the `:options` option. For example:
349
-
350
- ```ruby
351
- create_table :products, options: "ENGINE=BLACKHOLE" do |t|
352
- t.string :name, null: false
353
- end
354
- ```
355
-
356
- will append `ENGINE=BLACKHOLE` to the SQL statement used to create the table
357
- (when using MySQL, the default is `ENGINE=InnoDB`).
358
-
359
- ### Creating a Join Table
360
-
361
- Migration method `create_join_table` creates a HABTM join table. A typical use
362
- would be:
363
-
364
- ```ruby
365
- create_join_table :products, :categories
366
- ```
367
-
368
- which creates a `categories_products` table with two columns called
369
- `category_id` and `product_id`. These columns have the option `:null` set to
370
- `false` by default. This can be overridden by specifying the `:column_options`
371
- option.
372
-
373
- ```ruby
374
- create_join_table :products, :categories, column_options: {null: true}
375
- ```
376
-
377
- will create the `product_id` and `category_id` with the `:null` option as
378
- `true`.
379
-
380
- You can pass the option `:table_name` when you want to customize the table
381
- name. For example:
382
-
383
- ```ruby
384
- create_join_table :products, :categories, table_name: :categorization
385
- ```
386
-
387
- will create a `categorization` table.
388
-
389
- `create_join_table` also accepts a block, which you can use to add indices
390
- (which are not created by default) or additional columns:
391
-
392
- ```ruby
393
- create_join_table :products, :categories do |t|
394
- t.index :product_id
395
- t.index :category_id
396
- end
397
- ```
398
-
399
- ### Changing Tables
400
-
401
- A close cousin of `create_table` is `change_table`, used for changing existing
402
- tables. It is used in a similar fashion to `create_table` but the object
403
- yielded to the block knows more tricks. For example:
404
-
405
- ```ruby
406
- change_table :products do |t|
407
- t.remove :description, :name
408
- t.string :part_number
409
- t.index :part_number
410
- t.rename :upccode, :upc_code
411
- end
412
- ```
413
-
414
- removes the `description` and `name` columns, creates a `part_number` string
415
- column and adds an index on it. Finally it renames the `upccode` column.
416
-
417
- ### When Helpers aren't Enough
418
-
419
- If the helpers provided by Active Record aren't enough you can use the `execute`
420
- method to execute arbitrary SQL:
421
-
422
- ```ruby
423
- Product.connection.execute('UPDATE `products` SET `price`=`free` WHERE 1')
424
- ```
425
-
426
- For more details and examples of individual methods, check the API documentation.
427
- In particular the documentation for
428
- [`ActiveRecord::ConnectionAdapters::SchemaStatements`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html)
429
- (which provides the methods available in the `change`, `up` and `down` methods),
430
- [`ActiveRecord::ConnectionAdapters::TableDefinition`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html)
431
- (which provides the methods available on the object yielded by `create_table`)
432
- and
433
- [`ActiveRecord::ConnectionAdapters::Table`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html)
434
- (which provides the methods available on the object yielded by `change_table`).
435
-
436
- ### Using the `change` Method
437
-
438
- The `change` method is the primary way of writing migrations. It works for the
439
- majority of cases, where Active Record knows how to reverse the migration
440
- automatically. Currently, the `change` method supports only these migration
441
- definitions:
442
-
443
- * `add_column`
444
- * `add_index`
445
- * `add_reference`
446
- * `add_timestamps`
447
- * `create_table`
448
- * `create_join_table`
449
- * `drop_table` (must supply a block)
450
- * `drop_join_table` (must supply a block)
451
- * `remove_timestamps`
452
- * `rename_column`
453
- * `rename_index`
454
- * `remove_reference`
455
- * `rename_table`
456
-
457
- `change_table` is also reversible, as long as the block does not call `change`,
458
- `change_default` or `remove`.
459
-
460
- If you're going to need to use any other methods, you should use `reversible`
461
- or write the `up` and `down` methods instead of using the `change` method.
462
-
463
- ### Using `reversible`
464
-
465
- Complex migrations may require processing that Active Record doesn't know how
466
- to reverse. You can use `reversible` to specify what to do when running a
467
- migration what else to do when reverting it. For example:
468
-
469
- ```ruby
470
- class ExampleMigration < ActiveRecord::Migration
471
- def change
472
- create_table :products do |t|
473
- t.references :category
474
- end
475
-
476
- reversible do |dir|
477
- dir.up do
478
- #add a foreign key
479
- execute <<-SQL
480
- ALTER TABLE products
481
- ADD CONSTRAINT fk_products_categories
482
- FOREIGN KEY (category_id)
483
- REFERENCES categories(id)
484
- SQL
485
- end
486
- dir.down do
487
- execute <<-SQL
488
- ALTER TABLE products
489
- DROP FOREIGN KEY fk_products_categories
490
- SQL
491
- end
492
- end
493
-
494
- add_column :users, :home_page_url, :string
495
- rename_column :users, :email, :email_address
496
- end
497
- ```
498
-
499
- Using `reversible` will ensure that the instructions are executed in the
500
- right order too. If the previous example migration is reverted,
501
- the `down` block will be run after the `home_page_url` column is removed and
502
- right before the table `products` is dropped.
503
-
504
- Sometimes your migration will do something which is just plain irreversible; for
505
- example, it might destroy some data. In such cases, you can raise
506
- `ActiveRecord::IrreversibleMigration` in your `down` block. If someone tries
507
- to revert your migration, an error message will be displayed saying that it
508
- can't be done.
509
-
510
- ### Using the `up`/`down` Methods
511
-
512
- You can also use the old style of migration using `up` and `down` methods
513
- instead of the `change` method.
514
- The `up` method should describe the transformation you'd like to make to your
515
- schema, and the `down` method of your migration should revert the
516
- transformations done by the `up` method. In other words, the database schema
517
- should be unchanged if you do an `up` followed by a `down`. For example, if you
518
- create a table in the `up` method, you should drop it in the `down` method. It
519
- is wise to reverse the transformations in precisely the reverse order they were
520
- made in the `up` method. The example in the `reversible` section is equivalent to:
521
-
522
- ```ruby
523
- class ExampleMigration < ActiveRecord::Migration
524
- def up
525
- create_table :products do |t|
526
- t.references :category
527
- end
528
-
529
- # add a foreign key
530
- execute <<-SQL
531
- ALTER TABLE products
532
- ADD CONSTRAINT fk_products_categories
533
- FOREIGN KEY (category_id)
534
- REFERENCES categories(id)
535
- SQL
536
-
537
- add_column :users, :home_page_url, :string
538
- rename_column :users, :email, :email_address
539
- end
540
-
541
- def down
542
- rename_column :users, :email_address, :email
543
- remove_column :users, :home_page_url
544
-
545
- execute <<-SQL
546
- ALTER TABLE products
547
- DROP FOREIGN KEY fk_products_categories
548
- SQL
549
-
550
- drop_table :products
551
- end
552
- end
553
- ```
554
-
555
- If your migration is irreversible, you should raise
556
- `ActiveRecord::IrreversibleMigration` from your `down` method. If someone tries
557
- to revert your migration, an error message will be displayed saying that it
558
- can't be done.
559
-
560
- ### Reverting Previous Migrations
561
-
562
- You can use Active Record's ability to rollback migrations using the `revert` method:
563
-
564
- ```ruby
565
- require_relative '2012121212_example_migration'
566
-
567
- class FixupExampleMigration < ActiveRecord::Migration
568
- def change
569
- revert ExampleMigration
570
-
571
- create_table(:apples) do |t|
572
- t.string :variety
573
- end
574
- end
575
- end
576
- ```
577
-
578
- The `revert` method also accepts a block of instructions to reverse.
579
- This could be useful to revert selected parts of previous migrations.
580
- For example, let's imagine that `ExampleMigration` is committed and it
581
- is later decided it would be best to serialize the product list instead.
582
- One could write:
583
-
584
- ```ruby
585
- class SerializeProductListMigration < ActiveRecord::Migration
586
- def change
587
- add_column :categories, :product_list
588
-
589
- reversible do |dir|
590
- dir.up do
591
- # transfer data from Products to Category#product_list
592
- end
593
- dir.down do
594
- # create Products from Category#product_list
595
- end
596
- end
597
-
598
- revert do
599
- # copy-pasted code from ExampleMigration
600
- create_table :products do |t|
601
- t.references :category
602
- end
603
-
604
- reversible do |dir|
605
- dir.up do
606
- #add a foreign key
607
- execute <<-SQL
608
- ALTER TABLE products
609
- ADD CONSTRAINT fk_products_categories
610
- FOREIGN KEY (category_id)
611
- REFERENCES categories(id)
612
- SQL
613
- end
614
- dir.down do
615
- execute <<-SQL
616
- ALTER TABLE products
617
- DROP FOREIGN KEY fk_products_categories
618
- SQL
619
- end
620
- end
621
-
622
- # The rest of the migration was ok
623
- end
624
- end
625
- end
626
- ```
627
-
628
- The same migration could also have been written without using `revert`
629
- but this would have involved a few more steps: reversing the order
630
- of `create_table` and `reversible`, replacing `create_table`
631
- by `drop_table`, and finally replacing `up` by `down` and vice-versa.
632
- This is all taken care of by `revert`.
633
-
634
- Running Migrations
635
- ------------------
636
-
637
- Rails provides a set of Rake tasks to run certain sets of migrations.
638
-
639
- The very first migration related Rake task you will use will probably be
640
- `rake db:migrate`. In its most basic form it just runs the `change` or `up`
641
- method for all the migrations that have not yet been run. If there are
642
- no such migrations, it exits. It will run these migrations in order based
643
- on the date of the migration.
644
-
645
- Note that running the `db:migrate` task also invokes the `db:schema:dump` task, which
646
- will update your `db/schema.rb` file to match the structure of your database.
647
-
648
- If you specify a target version, Active Record will run the required migrations
649
- (change, up, down) until it has reached the specified version. The version
650
- is the numerical prefix on the migration's filename. For example, to migrate
651
- to version 20080906120000 run:
652
-
653
- ```bash
654
- $ rake db:migrate VERSION=20080906120000
655
- ```
656
-
657
- If version 20080906120000 is greater than the current version (i.e., it is
658
- migrating upwards), this will run the `change` (or `up`) method
659
- on all migrations up to and
660
- including 20080906120000, and will not execute any later migrations. If
661
- migrating downwards, this will run the `down` method on all the migrations
662
- down to, but not including, 20080906120000.
663
-
664
- ### Rolling Back
665
-
666
- A common task is to rollback the last migration. For example, if you made a
667
- mistake in it and wish to correct it. Rather than tracking down the version
668
- number associated with the previous migration you can run:
669
-
670
- ```bash
671
- $ rake db:rollback
672
- ```
673
-
674
- This will rollback the latest migration, either by reverting the `change`
675
- method or by running the `down` method. If you need to undo
676
- several migrations you can provide a `STEP` parameter:
677
-
678
- ```bash
679
- $ rake db:rollback STEP=3
680
- ```
681
-
682
- will revert the last 3 migrations.
683
-
684
- The `db:migrate:redo` task is a shortcut for doing a rollback and then migrating
685
- back up again. As with the `db:rollback` task, you can use the `STEP` parameter
686
- if you need to go more than one version back, for example:
687
-
688
- ```bash
689
- $ rake db:migrate:redo STEP=3
690
- ```
691
-
692
- Neither of these Rake tasks do anything you could not do with `db:migrate`. They
693
- are simply more convenient, since you do not need to explicitly specify the
694
- version to migrate to.
695
-
696
- ### Setup the Database
697
-
698
- The `rake db:setup` task will create the database, load the schema and initialize
699
- it with the seed data.
700
-
701
- ### Resetting the Database
702
-
703
- The `rake db:reset` task will drop the database and set it up again. This is
704
- functionally equivalent to `rake db:drop db:setup`.
705
-
706
- NOTE: This is not the same as running all the migrations. It will only use the
707
- contents of the current `schema.rb` file. If a migration can't be rolled back,
708
- `rake db:reset` may not help you. To find out more about dumping the schema see
709
- [Schema Dumping and You](#schema-dumping-and-you) section.
710
-
711
- ### Running Specific Migrations
712
-
713
- If you need to run a specific migration up or down, the `db:migrate:up` and
714
- `db:migrate:down` tasks will do that. Just specify the appropriate version and
715
- the corresponding migration will have its `change`, `up` or `down` method
716
- invoked, for example:
717
-
718
- ```bash
719
- $ rake db:migrate:up VERSION=20080906120000
720
- ```
721
-
722
- will run the 20080906120000 migration by running the `change` method (or the
723
- `up` method). This task will
724
- first check whether the migration is already performed and will do nothing if
725
- Active Record believes that it has already been run.
726
-
727
- ### Running Migrations in Different Environments
728
-
729
- By default running `rake db:migrate` will run in the `development` environment.
730
- To run migrations against another environment you can specify it using the
731
- `RAILS_ENV` environment variable while running the command. For example to run
732
- migrations against the `test` environment you could run:
733
-
734
- ```bash
735
- $ rake db:migrate RAILS_ENV=test
736
- ```
737
-
738
- ### Changing the Output of Running Migrations
739
-
740
- By default migrations tell you exactly what they're doing and how long it took.
741
- A migration creating a table and adding an index might produce output like this
742
-
743
- ```bash
744
- == CreateProducts: migrating =================================================
745
- -- create_table(:products)
746
- -> 0.0028s
747
- == CreateProducts: migrated (0.0028s) ========================================
748
- ```
749
-
750
- Several methods are provided in migrations that allow you to control all this:
751
-
752
- | Method | Purpose
753
- | -------------------- | -------
754
- | suppress_messages | Takes a block as an argument and suppresses any output generated by the block.
755
- | say | Takes a message argument and outputs it as is. A second boolean argument can be passed to specify whether to indent or not.
756
- | say_with_time | Outputs text along with how long it took to run its block. If the block returns an integer it assumes it is the number of rows affected.
757
-
758
- For example, this migration:
759
-
760
- ```ruby
761
- class CreateProducts < ActiveRecord::Migration
762
- def change
763
- suppress_messages do
764
- create_table :products do |t|
765
- t.string :name
766
- t.text :description
767
- t.timestamps
768
- end
769
- end
770
-
771
- say "Created a table"
772
-
773
- suppress_messages {add_index :products, :name}
774
- say "and an index!", true
775
-
776
- say_with_time 'Waiting for a while' do
777
- sleep 10
778
- 250
779
- end
780
- end
781
- end
782
- ```
783
-
784
- generates the following output
785
-
786
- ```bash
787
- == CreateProducts: migrating =================================================
788
- -- Created a table
789
- -> and an index!
790
- -- Waiting for a while
791
- -> 10.0013s
792
- -> 250 rows
793
- == CreateProducts: migrated (10.0054s) =======================================
794
- ```
795
-
796
- If you want Active Record to not output anything, then running `rake db:migrate
797
- VERBOSE=false` will suppress all output.
798
-
799
- Changing Existing Migrations
800
- ----------------------------
801
-
802
- Occasionally you will make a mistake when writing a migration. If you have
803
- already run the migration then you cannot just edit the migration and run the
804
- migration again: Rails thinks it has already run the migration and so will do
805
- nothing when you run `rake db:migrate`. You must rollback the migration (for
806
- example with `rake db:rollback`), edit your migration and then run
807
- `rake db:migrate` to run the corrected version.
808
-
809
- In general, editing existing migrations is not a good idea. You will be
810
- creating extra work for yourself and your co-workers and cause major headaches
811
- if the existing version of the migration has already been run on production
812
- machines. Instead, you should write a new migration that performs the changes
813
- you require. Editing a freshly generated migration that has not yet been
814
- committed to source control (or, more generally, which has not been propagated
815
- beyond your development machine) is relatively harmless.
816
-
817
- The `revert` method can be helpful when writing a new migration to undo
818
- previous migrations in whole or in part
819
- (see [Reverting Previous Migrations](#reverting-previous-migrations) above).
820
-
821
- Using Models in Your Migrations
822
- -------------------------------
823
-
824
- When creating or updating data in a migration it is often tempting to use one
825
- of your models. After all, they exist to provide easy access to the underlying
826
- data. This can be done, but some caution should be observed.
827
-
828
- For example, problems occur when the model uses database columns which are (1)
829
- not currently in the database and (2) will be created by this or a subsequent
830
- migration.
831
-
832
- Consider this example, where Alice and Bob are working on the same code base
833
- which contains a `Product` model:
834
-
835
- Bob goes on vacation.
836
-
837
- Alice creates a migration for the `products` table which adds a new column and
838
- initializes it:
839
-
840
- ```ruby
841
- # db/migrate/20100513121110_add_flag_to_product.rb
842
-
843
- class AddFlagToProduct < ActiveRecord::Migration
844
- def change
845
- add_column :products, :flag, :boolean
846
- reversible do |dir|
847
- dir.up { Product.update_all flag: false }
848
- end
849
- end
850
- end
851
- ```
852
-
853
- She also adds a validation to the `Product` model for the new column:
854
-
855
- ```ruby
856
- # app/models/product.rb
857
-
858
- class Product < ActiveRecord::Base
859
- validates :flag, inclusion: { in: [true, false] }
860
- end
861
- ```
862
-
863
- Alice adds a second migration which adds another column to the `products`
864
- table and initializes it:
865
-
866
- ```ruby
867
- # db/migrate/20100515121110_add_fuzz_to_product.rb
868
-
869
- class AddFuzzToProduct < ActiveRecord::Migration
870
- def change
871
- add_column :products, :fuzz, :string
872
- reversible do |dir|
873
- dir.up { Product.update_all fuzz: 'fuzzy' }
874
- end
875
- end
876
- end
877
- ```
878
-
879
- She also adds a validation to the `Product` model for the new column:
880
-
881
- ```ruby
882
- # app/models/product.rb
883
-
884
- class Product < ActiveRecord::Base
885
- validates :flag, inclusion: { in: [true, false] }
886
- validates :fuzz, presence: true
887
- end
888
- ```
889
-
890
- Both migrations work for Alice.
891
-
892
- Bob comes back from vacation and:
893
-
894
- * Updates the source - which contains both migrations and the latest version
895
- of the Product model.
896
- * Runs outstanding migrations with `rake db:migrate`, which
897
- includes the one that updates the `Product` model.
898
-
899
- The migration crashes because when the model attempts to save, it tries to
900
- validate the second added column, which is not in the database when the _first_
901
- migration runs:
902
-
903
- ```
904
- rake aborted!
905
- An error has occurred, this and all later migrations canceled:
906
-
907
- undefined method `fuzz' for #<Product:0x000001049b14a0>
908
- ```
909
-
910
- A fix for this is to create a local model within the migration. This keeps
911
- Rails from running the validations, so that the migrations run to completion.
912
-
913
- When using a local model, it's a good idea to call
914
- `Product.reset_column_information` to refresh the Active Record cache for the
915
- `Product` model prior to updating data in the database.
916
-
917
- If Alice had done this instead, there would have been no problem:
918
-
919
- ```ruby
920
- # db/migrate/20100513121110_add_flag_to_product.rb
921
-
922
- class AddFlagToProduct < ActiveRecord::Migration
923
- class Product < ActiveRecord::Base
924
- end
925
-
926
- def change
927
- add_column :products, :flag, :boolean
928
- Product.reset_column_information
929
- reversible do |dir|
930
- dir.up { Product.update_all flag: false }
931
- end
932
- end
933
- end
934
- ```
935
-
936
- ```ruby
937
- # db/migrate/20100515121110_add_fuzz_to_product.rb
938
-
939
- class AddFuzzToProduct < ActiveRecord::Migration
940
- class Product < ActiveRecord::Base
941
- end
942
-
943
- def change
944
- add_column :products, :fuzz, :string
945
- Product.reset_column_information
946
- reversible do |dir|
947
- dir.up { Product.update_all fuzz: 'fuzzy' }
948
- end
949
- end
950
- end
951
- ```
952
-
953
- There are other ways in which the above example could have gone badly.
954
-
955
- For example, imagine that Alice creates a migration that selectively
956
- updates the `description` field on certain products. She runs the
957
- migration, commits the code, and then begins working on the next feature,
958
- which is to add a new column `fuzz` to the products table.
959
-
960
- She creates two migrations for this new feature, one which adds the new
961
- column, and a second which selectively updates the `fuzz` column based on
962
- other product attributes.
963
-
964
- These migrations run just fine, but when Bob comes back from his vacation
965
- and calls `rake db:migrate` to run all the outstanding migrations, he gets a
966
- subtle bug: The descriptions have defaults, and the `fuzz` column is present,
967
- but `fuzz` is `nil` on all products.
968
-
969
- The solution is again to use `Product.reset_column_information` before
970
- referencing the Product model in a migration, ensuring the Active Record's
971
- knowledge of the table structure is current before manipulating data in those
972
- records.
973
-
974
- Schema Dumping and You
975
- ----------------------
976
-
977
- ### What are Schema Files for?
978
-
979
- Migrations, mighty as they may be, are not the authoritative source for your
980
- database schema. That role falls to either `db/schema.rb` or an SQL file which
981
- Active Record generates by examining the database. They are not designed to be
982
- edited, they just represent the current state of the database.
983
-
984
- There is no need (and it is error prone) to deploy a new instance of an app by
985
- replaying the entire migration history. It is much simpler and faster to just
986
- load into the database a description of the current schema.
987
-
988
- For example, this is how the test database is created: the current development
989
- database is dumped (either to `db/schema.rb` or `db/structure.sql`) and then
990
- loaded into the test database.
991
-
992
- Schema files are also useful if you want a quick look at what attributes an
993
- Active Record object has. This information is not in the model's code and is
994
- frequently spread across several migrations, but the information is nicely
995
- summed up in the schema file. The
996
- [annotate_models](https://github.com/ctran/annotate_models) gem automatically
997
- adds and updates comments at the top of each model summarizing the schema if
998
- you desire that functionality.
999
-
1000
- ### Types of Schema Dumps
1001
-
1002
- There are two ways to dump the schema. This is set in `config/application.rb`
1003
- by the `config.active_record.schema_format` setting, which may be either `:sql`
1004
- or `:ruby`.
1005
-
1006
- If `:ruby` is selected then the schema is stored in `db/schema.rb`. If you look
1007
- at this file you'll find that it looks an awful lot like one very big
1008
- migration:
1009
-
1010
- ```ruby
1011
- ActiveRecord::Schema.define(version: 20080906171750) do
1012
- create_table "authors", force: true do |t|
1013
- t.string "name"
1014
- t.datetime "created_at"
1015
- t.datetime "updated_at"
1016
- end
1017
-
1018
- create_table "products", force: true do |t|
1019
- t.string "name"
1020
- t.text "description"
1021
- t.datetime "created_at"
1022
- t.datetime "updated_at"
1023
- t.string "part_number"
1024
- end
1025
- end
1026
- ```
1027
-
1028
- In many ways this is exactly what it is. This file is created by inspecting the
1029
- database and expressing its structure using `create_table`, `add_index`, and so
1030
- on. Because this is database-independent, it could be loaded into any database
1031
- that Active Record supports. This could be very useful if you were to
1032
- distribute an application that is able to run against multiple databases.
1033
-
1034
- There is however a trade-off: `db/schema.rb` cannot express database specific
1035
- items such as foreign key constraints, triggers, or stored procedures. While in
1036
- a migration you can execute custom SQL statements, the schema dumper cannot
1037
- reconstitute those statements from the database. If you are using features like
1038
- this, then you should set the schema format to `:sql`.
1039
-
1040
- Instead of using Active Record's schema dumper, the database's structure will
1041
- be dumped using a tool specific to the database (via the `db:structure:dump`
1042
- Rake task) into `db/structure.sql`. For example, for PostgreSQL, the `pg_dump`
1043
- utility is used. For MySQL, this file will contain the output of
1044
- `SHOW CREATE TABLE` for the various tables.
1045
-
1046
- Loading these schemas is simply a question of executing the SQL statements they
1047
- contain. By definition, this will create a perfect copy of the database's
1048
- structure. Using the `:sql` schema format will, however, prevent loading the
1049
- schema into a RDBMS other than the one used to create it.
1050
-
1051
- ### Schema Dumps and Source Control
1052
-
1053
- Because schema dumps are the authoritative source for your database schema, it
1054
- is strongly recommended that you check them into source control.
1055
-
1056
- Active Record and Referential Integrity
1057
- ---------------------------------------
1058
-
1059
- The Active Record way claims that intelligence belongs in your models, not in
1060
- the database. As such, features such as triggers or foreign key constraints,
1061
- which push some of that intelligence back into the database, are not heavily
1062
- used.
1063
-
1064
- Validations such as `validates :foreign_key, uniqueness: true` are one way in
1065
- which models can enforce data integrity. The `:dependent` option on
1066
- associations allows models to automatically destroy child objects when the
1067
- parent is destroyed. Like anything which operates at the application level,
1068
- these cannot guarantee referential integrity and so some people augment them
1069
- with foreign key constraints in the database.
1070
-
1071
- Although Active Record does not provide any tools for working directly with
1072
- such features, the `execute` method can be used to execute arbitrary SQL. You
1073
- can also use a gem like
1074
- [foreigner](https://github.com/matthuhiggins/foreigner) which adds foreign key
1075
- support to Active Record (including support for dumping foreign keys in
1076
- `db/schema.rb`).
1077
-
1078
- Migrations and Seed Data
1079
- ------------------------
1080
-
1081
- Some people use migrations to add data to the database:
1082
-
1083
- ```ruby
1084
- class AddInitialProducts < ActiveRecord::Migration
1085
- def up
1086
- 5.times do |i|
1087
- Product.create(name: "Product ##{i}", description: "A product.")
1088
- end
1089
- end
1090
-
1091
- def down
1092
- Product.delete_all
1093
- end
1094
- end
1095
- ```
1096
-
1097
- However, Rails has a 'seeds' feature that should be used for seeding a database
1098
- with initial data. It's a really simple feature: just fill up `db/seeds.rb`
1099
- with some Ruby code, and run `rake db:seed`:
1100
-
1101
- ```ruby
1102
- 5.times do |i|
1103
- Product.create(name: "Product ##{i}", description: "A product.")
1104
- end
1105
- ```
1106
-
1107
- This is generally a much cleaner way to set up the database of a blank
1108
- application.