rails 4.1.4 → 5.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (284) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +24 -18
  3. metadata +51 -304
  4. data/guides/CHANGELOG.md +0 -41
  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 -125
  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/application.rb +0 -18
  182. data/guides/code/getting_started/config/boot.rb +0 -4
  183. data/guides/code/getting_started/config/database.yml +0 -25
  184. data/guides/code/getting_started/config/environment.rb +0 -5
  185. data/guides/code/getting_started/config/environments/development.rb +0 -30
  186. data/guides/code/getting_started/config/environments/production.rb +0 -80
  187. data/guides/code/getting_started/config/environments/test.rb +0 -36
  188. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
  189. data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
  190. data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
  191. data/guides/code/getting_started/config/initializers/locale.rb +0 -9
  192. data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
  193. data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
  194. data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
  195. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
  196. data/guides/code/getting_started/config/locales/en.yml +0 -23
  197. data/guides/code/getting_started/config/routes.rb +0 -7
  198. data/guides/code/getting_started/config.ru +0 -4
  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 -12
  219. data/guides/rails_guides/generator.rb +0 -248
  220. data/guides/rails_guides/helpers.rb +0 -53
  221. data/guides/rails_guides/indexer.rb +0 -68
  222. data/guides/rails_guides/kindle.rb +0 -119
  223. data/guides/rails_guides/levenshtein.rb +0 -31
  224. data/guides/rails_guides/markdown/renderer.rb +0 -82
  225. data/guides/rails_guides/markdown.rb +0 -163
  226. data/guides/rails_guides.rb +0 -63
  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 -25
  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 -1773
  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 -315
  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 -193
  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 -1109
  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 -1052
  282. data/guides/source/upgrading_ruby_on_rails.md +0 -899
  283. data/guides/source/working_with_javascript_in_rails.md +0 -405
  284. data/guides/w3c_validator.rb +0 -95
@@ -1,1109 +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
- $ bin/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
- $ bin/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
- $ bin/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
- $ bin/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
- $ bin/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
- $ bin/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
- $ bin/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
- $ bin/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
- $ bin/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
- $ bin/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
- end
498
- ```
499
-
500
- Using `reversible` will ensure that the instructions are executed in the
501
- right order too. If the previous example migration is reverted,
502
- the `down` block will be run after the `home_page_url` column is removed and
503
- right before the table `products` is dropped.
504
-
505
- Sometimes your migration will do something which is just plain irreversible; for
506
- example, it might destroy some data. In such cases, you can raise
507
- `ActiveRecord::IrreversibleMigration` in your `down` block. If someone tries
508
- to revert your migration, an error message will be displayed saying that it
509
- can't be done.
510
-
511
- ### Using the `up`/`down` Methods
512
-
513
- You can also use the old style of migration using `up` and `down` methods
514
- instead of the `change` method.
515
- The `up` method should describe the transformation you'd like to make to your
516
- schema, and the `down` method of your migration should revert the
517
- transformations done by the `up` method. In other words, the database schema
518
- should be unchanged if you do an `up` followed by a `down`. For example, if you
519
- create a table in the `up` method, you should drop it in the `down` method. It
520
- is wise to reverse the transformations in precisely the reverse order they were
521
- made in the `up` method. The example in the `reversible` section is equivalent to:
522
-
523
- ```ruby
524
- class ExampleMigration < ActiveRecord::Migration
525
- def up
526
- create_table :products do |t|
527
- t.references :category
528
- end
529
-
530
- # add a foreign key
531
- execute <<-SQL
532
- ALTER TABLE products
533
- ADD CONSTRAINT fk_products_categories
534
- FOREIGN KEY (category_id)
535
- REFERENCES categories(id)
536
- SQL
537
-
538
- add_column :users, :home_page_url, :string
539
- rename_column :users, :email, :email_address
540
- end
541
-
542
- def down
543
- rename_column :users, :email_address, :email
544
- remove_column :users, :home_page_url
545
-
546
- execute <<-SQL
547
- ALTER TABLE products
548
- DROP FOREIGN KEY fk_products_categories
549
- SQL
550
-
551
- drop_table :products
552
- end
553
- end
554
- ```
555
-
556
- If your migration is irreversible, you should raise
557
- `ActiveRecord::IrreversibleMigration` from your `down` method. If someone tries
558
- to revert your migration, an error message will be displayed saying that it
559
- can't be done.
560
-
561
- ### Reverting Previous Migrations
562
-
563
- You can use Active Record's ability to rollback migrations using the `revert` method:
564
-
565
- ```ruby
566
- require_relative '2012121212_example_migration'
567
-
568
- class FixupExampleMigration < ActiveRecord::Migration
569
- def change
570
- revert ExampleMigration
571
-
572
- create_table(:apples) do |t|
573
- t.string :variety
574
- end
575
- end
576
- end
577
- ```
578
-
579
- The `revert` method also accepts a block of instructions to reverse.
580
- This could be useful to revert selected parts of previous migrations.
581
- For example, let's imagine that `ExampleMigration` is committed and it
582
- is later decided it would be best to serialize the product list instead.
583
- One could write:
584
-
585
- ```ruby
586
- class SerializeProductListMigration < ActiveRecord::Migration
587
- def change
588
- add_column :categories, :product_list
589
-
590
- reversible do |dir|
591
- dir.up do
592
- # transfer data from Products to Category#product_list
593
- end
594
- dir.down do
595
- # create Products from Category#product_list
596
- end
597
- end
598
-
599
- revert do
600
- # copy-pasted code from ExampleMigration
601
- create_table :products do |t|
602
- t.references :category
603
- end
604
-
605
- reversible do |dir|
606
- dir.up do
607
- #add a foreign key
608
- execute <<-SQL
609
- ALTER TABLE products
610
- ADD CONSTRAINT fk_products_categories
611
- FOREIGN KEY (category_id)
612
- REFERENCES categories(id)
613
- SQL
614
- end
615
- dir.down do
616
- execute <<-SQL
617
- ALTER TABLE products
618
- DROP FOREIGN KEY fk_products_categories
619
- SQL
620
- end
621
- end
622
-
623
- # The rest of the migration was ok
624
- end
625
- end
626
- end
627
- ```
628
-
629
- The same migration could also have been written without using `revert`
630
- but this would have involved a few more steps: reversing the order
631
- of `create_table` and `reversible`, replacing `create_table`
632
- by `drop_table`, and finally replacing `up` by `down` and vice-versa.
633
- This is all taken care of by `revert`.
634
-
635
- Running Migrations
636
- ------------------
637
-
638
- Rails provides a set of Rake tasks to run certain sets of migrations.
639
-
640
- The very first migration related Rake task you will use will probably be
641
- `rake db:migrate`. In its most basic form it just runs the `change` or `up`
642
- method for all the migrations that have not yet been run. If there are
643
- no such migrations, it exits. It will run these migrations in order based
644
- on the date of the migration.
645
-
646
- Note that running the `db:migrate` task also invokes the `db:schema:dump` task, which
647
- will update your `db/schema.rb` file to match the structure of your database.
648
-
649
- If you specify a target version, Active Record will run the required migrations
650
- (change, up, down) until it has reached the specified version. The version
651
- is the numerical prefix on the migration's filename. For example, to migrate
652
- to version 20080906120000 run:
653
-
654
- ```bash
655
- $ bin/rake db:migrate VERSION=20080906120000
656
- ```
657
-
658
- If version 20080906120000 is greater than the current version (i.e., it is
659
- migrating upwards), this will run the `change` (or `up`) method
660
- on all migrations up to and
661
- including 20080906120000, and will not execute any later migrations. If
662
- migrating downwards, this will run the `down` method on all the migrations
663
- down to, but not including, 20080906120000.
664
-
665
- ### Rolling Back
666
-
667
- A common task is to rollback the last migration. For example, if you made a
668
- mistake in it and wish to correct it. Rather than tracking down the version
669
- number associated with the previous migration you can run:
670
-
671
- ```bash
672
- $ bin/rake db:rollback
673
- ```
674
-
675
- This will rollback the latest migration, either by reverting the `change`
676
- method or by running the `down` method. If you need to undo
677
- several migrations you can provide a `STEP` parameter:
678
-
679
- ```bash
680
- $ bin/rake db:rollback STEP=3
681
- ```
682
-
683
- will revert the last 3 migrations.
684
-
685
- The `db:migrate:redo` task is a shortcut for doing a rollback and then migrating
686
- back up again. As with the `db:rollback` task, you can use the `STEP` parameter
687
- if you need to go more than one version back, for example:
688
-
689
- ```bash
690
- $ bin/rake db:migrate:redo STEP=3
691
- ```
692
-
693
- Neither of these Rake tasks do anything you could not do with `db:migrate`. They
694
- are simply more convenient, since you do not need to explicitly specify the
695
- version to migrate to.
696
-
697
- ### Setup the Database
698
-
699
- The `rake db:setup` task will create the database, load the schema and initialize
700
- it with the seed data.
701
-
702
- ### Resetting the Database
703
-
704
- The `rake db:reset` task will drop the database and set it up again. This is
705
- functionally equivalent to `rake db:drop db:setup`.
706
-
707
- NOTE: This is not the same as running all the migrations. It will only use the
708
- contents of the current `schema.rb` file. If a migration can't be rolled back,
709
- `rake db:reset` may not help you. To find out more about dumping the schema see
710
- [Schema Dumping and You](#schema-dumping-and-you) section.
711
-
712
- ### Running Specific Migrations
713
-
714
- If you need to run a specific migration up or down, the `db:migrate:up` and
715
- `db:migrate:down` tasks will do that. Just specify the appropriate version and
716
- the corresponding migration will have its `change`, `up` or `down` method
717
- invoked, for example:
718
-
719
- ```bash
720
- $ bin/rake db:migrate:up VERSION=20080906120000
721
- ```
722
-
723
- will run the 20080906120000 migration by running the `change` method (or the
724
- `up` method). This task will
725
- first check whether the migration is already performed and will do nothing if
726
- Active Record believes that it has already been run.
727
-
728
- ### Running Migrations in Different Environments
729
-
730
- By default running `rake db:migrate` will run in the `development` environment.
731
- To run migrations against another environment you can specify it using the
732
- `RAILS_ENV` environment variable while running the command. For example to run
733
- migrations against the `test` environment you could run:
734
-
735
- ```bash
736
- $ bin/rake db:migrate RAILS_ENV=test
737
- ```
738
-
739
- ### Changing the Output of Running Migrations
740
-
741
- By default migrations tell you exactly what they're doing and how long it took.
742
- A migration creating a table and adding an index might produce output like this
743
-
744
- ```bash
745
- == CreateProducts: migrating =================================================
746
- -- create_table(:products)
747
- -> 0.0028s
748
- == CreateProducts: migrated (0.0028s) ========================================
749
- ```
750
-
751
- Several methods are provided in migrations that allow you to control all this:
752
-
753
- | Method | Purpose
754
- | -------------------- | -------
755
- | suppress_messages | Takes a block as an argument and suppresses any output generated by the block.
756
- | say | Takes a message argument and outputs it as is. A second boolean argument can be passed to specify whether to indent or not.
757
- | 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.
758
-
759
- For example, this migration:
760
-
761
- ```ruby
762
- class CreateProducts < ActiveRecord::Migration
763
- def change
764
- suppress_messages do
765
- create_table :products do |t|
766
- t.string :name
767
- t.text :description
768
- t.timestamps
769
- end
770
- end
771
-
772
- say "Created a table"
773
-
774
- suppress_messages {add_index :products, :name}
775
- say "and an index!", true
776
-
777
- say_with_time 'Waiting for a while' do
778
- sleep 10
779
- 250
780
- end
781
- end
782
- end
783
- ```
784
-
785
- generates the following output
786
-
787
- ```bash
788
- == CreateProducts: migrating =================================================
789
- -- Created a table
790
- -> and an index!
791
- -- Waiting for a while
792
- -> 10.0013s
793
- -> 250 rows
794
- == CreateProducts: migrated (10.0054s) =======================================
795
- ```
796
-
797
- If you want Active Record to not output anything, then running `rake db:migrate
798
- VERBOSE=false` will suppress all output.
799
-
800
- Changing Existing Migrations
801
- ----------------------------
802
-
803
- Occasionally you will make a mistake when writing a migration. If you have
804
- already run the migration then you cannot just edit the migration and run the
805
- migration again: Rails thinks it has already run the migration and so will do
806
- nothing when you run `rake db:migrate`. You must rollback the migration (for
807
- example with `rake db:rollback`), edit your migration and then run
808
- `rake db:migrate` to run the corrected version.
809
-
810
- In general, editing existing migrations is not a good idea. You will be
811
- creating extra work for yourself and your co-workers and cause major headaches
812
- if the existing version of the migration has already been run on production
813
- machines. Instead, you should write a new migration that performs the changes
814
- you require. Editing a freshly generated migration that has not yet been
815
- committed to source control (or, more generally, which has not been propagated
816
- beyond your development machine) is relatively harmless.
817
-
818
- The `revert` method can be helpful when writing a new migration to undo
819
- previous migrations in whole or in part
820
- (see [Reverting Previous Migrations](#reverting-previous-migrations) above).
821
-
822
- Using Models in Your Migrations
823
- -------------------------------
824
-
825
- When creating or updating data in a migration it is often tempting to use one
826
- of your models. After all, they exist to provide easy access to the underlying
827
- data. This can be done, but some caution should be observed.
828
-
829
- For example, problems occur when the model uses database columns which are (1)
830
- not currently in the database and (2) will be created by this or a subsequent
831
- migration.
832
-
833
- Consider this example, where Alice and Bob are working on the same code base
834
- which contains a `Product` model:
835
-
836
- Bob goes on vacation.
837
-
838
- Alice creates a migration for the `products` table which adds a new column and
839
- initializes it:
840
-
841
- ```ruby
842
- # db/migrate/20100513121110_add_flag_to_product.rb
843
-
844
- class AddFlagToProduct < ActiveRecord::Migration
845
- def change
846
- add_column :products, :flag, :boolean
847
- reversible do |dir|
848
- dir.up { Product.update_all flag: false }
849
- end
850
- end
851
- end
852
- ```
853
-
854
- She also adds a validation to the `Product` model for the new column:
855
-
856
- ```ruby
857
- # app/models/product.rb
858
-
859
- class Product < ActiveRecord::Base
860
- validates :flag, inclusion: { in: [true, false] }
861
- end
862
- ```
863
-
864
- Alice adds a second migration which adds another column to the `products`
865
- table and initializes it:
866
-
867
- ```ruby
868
- # db/migrate/20100515121110_add_fuzz_to_product.rb
869
-
870
- class AddFuzzToProduct < ActiveRecord::Migration
871
- def change
872
- add_column :products, :fuzz, :string
873
- reversible do |dir|
874
- dir.up { Product.update_all fuzz: 'fuzzy' }
875
- end
876
- end
877
- end
878
- ```
879
-
880
- She also adds a validation to the `Product` model for the new column:
881
-
882
- ```ruby
883
- # app/models/product.rb
884
-
885
- class Product < ActiveRecord::Base
886
- validates :flag, inclusion: { in: [true, false] }
887
- validates :fuzz, presence: true
888
- end
889
- ```
890
-
891
- Both migrations work for Alice.
892
-
893
- Bob comes back from vacation and:
894
-
895
- * Updates the source - which contains both migrations and the latest version
896
- of the Product model.
897
- * Runs outstanding migrations with `rake db:migrate`, which
898
- includes the one that updates the `Product` model.
899
-
900
- The migration crashes because when the model attempts to save, it tries to
901
- validate the second added column, which is not in the database when the _first_
902
- migration runs:
903
-
904
- ```
905
- rake aborted!
906
- An error has occurred, this and all later migrations canceled:
907
-
908
- undefined method `fuzz' for #<Product:0x000001049b14a0>
909
- ```
910
-
911
- A fix for this is to create a local model within the migration. This keeps
912
- Rails from running the validations, so that the migrations run to completion.
913
-
914
- When using a local model, it's a good idea to call
915
- `Product.reset_column_information` to refresh the Active Record cache for the
916
- `Product` model prior to updating data in the database.
917
-
918
- If Alice had done this instead, there would have been no problem:
919
-
920
- ```ruby
921
- # db/migrate/20100513121110_add_flag_to_product.rb
922
-
923
- class AddFlagToProduct < ActiveRecord::Migration
924
- class Product < ActiveRecord::Base
925
- end
926
-
927
- def change
928
- add_column :products, :flag, :boolean
929
- Product.reset_column_information
930
- reversible do |dir|
931
- dir.up { Product.update_all flag: false }
932
- end
933
- end
934
- end
935
- ```
936
-
937
- ```ruby
938
- # db/migrate/20100515121110_add_fuzz_to_product.rb
939
-
940
- class AddFuzzToProduct < ActiveRecord::Migration
941
- class Product < ActiveRecord::Base
942
- end
943
-
944
- def change
945
- add_column :products, :fuzz, :string
946
- Product.reset_column_information
947
- reversible do |dir|
948
- dir.up { Product.update_all fuzz: 'fuzzy' }
949
- end
950
- end
951
- end
952
- ```
953
-
954
- There are other ways in which the above example could have gone badly.
955
-
956
- For example, imagine that Alice creates a migration that selectively
957
- updates the `description` field on certain products. She runs the
958
- migration, commits the code, and then begins working on the next feature,
959
- which is to add a new column `fuzz` to the products table.
960
-
961
- She creates two migrations for this new feature, one which adds the new
962
- column, and a second which selectively updates the `fuzz` column based on
963
- other product attributes.
964
-
965
- These migrations run just fine, but when Bob comes back from his vacation
966
- and calls `rake db:migrate` to run all the outstanding migrations, he gets a
967
- subtle bug: The descriptions have defaults, and the `fuzz` column is present,
968
- but `fuzz` is `nil` on all products.
969
-
970
- The solution is again to use `Product.reset_column_information` before
971
- referencing the Product model in a migration, ensuring the Active Record's
972
- knowledge of the table structure is current before manipulating data in those
973
- records.
974
-
975
- Schema Dumping and You
976
- ----------------------
977
-
978
- ### What are Schema Files for?
979
-
980
- Migrations, mighty as they may be, are not the authoritative source for your
981
- database schema. That role falls to either `db/schema.rb` or an SQL file which
982
- Active Record generates by examining the database. They are not designed to be
983
- edited, they just represent the current state of the database.
984
-
985
- There is no need (and it is error prone) to deploy a new instance of an app by
986
- replaying the entire migration history. It is much simpler and faster to just
987
- load into the database a description of the current schema.
988
-
989
- For example, this is how the test database is created: the current development
990
- database is dumped (either to `db/schema.rb` or `db/structure.sql`) and then
991
- loaded into the test database.
992
-
993
- Schema files are also useful if you want a quick look at what attributes an
994
- Active Record object has. This information is not in the model's code and is
995
- frequently spread across several migrations, but the information is nicely
996
- summed up in the schema file. The
997
- [annotate_models](https://github.com/ctran/annotate_models) gem automatically
998
- adds and updates comments at the top of each model summarizing the schema if
999
- you desire that functionality.
1000
-
1001
- ### Types of Schema Dumps
1002
-
1003
- There are two ways to dump the schema. This is set in `config/application.rb`
1004
- by the `config.active_record.schema_format` setting, which may be either `:sql`
1005
- or `:ruby`.
1006
-
1007
- If `:ruby` is selected then the schema is stored in `db/schema.rb`. If you look
1008
- at this file you'll find that it looks an awful lot like one very big
1009
- migration:
1010
-
1011
- ```ruby
1012
- ActiveRecord::Schema.define(version: 20080906171750) do
1013
- create_table "authors", force: true do |t|
1014
- t.string "name"
1015
- t.datetime "created_at"
1016
- t.datetime "updated_at"
1017
- end
1018
-
1019
- create_table "products", force: true do |t|
1020
- t.string "name"
1021
- t.text "description"
1022
- t.datetime "created_at"
1023
- t.datetime "updated_at"
1024
- t.string "part_number"
1025
- end
1026
- end
1027
- ```
1028
-
1029
- In many ways this is exactly what it is. This file is created by inspecting the
1030
- database and expressing its structure using `create_table`, `add_index`, and so
1031
- on. Because this is database-independent, it could be loaded into any database
1032
- that Active Record supports. This could be very useful if you were to
1033
- distribute an application that is able to run against multiple databases.
1034
-
1035
- There is however a trade-off: `db/schema.rb` cannot express database specific
1036
- items such as foreign key constraints, triggers, or stored procedures. While in
1037
- a migration you can execute custom SQL statements, the schema dumper cannot
1038
- reconstitute those statements from the database. If you are using features like
1039
- this, then you should set the schema format to `:sql`.
1040
-
1041
- Instead of using Active Record's schema dumper, the database's structure will
1042
- be dumped using a tool specific to the database (via the `db:structure:dump`
1043
- Rake task) into `db/structure.sql`. For example, for PostgreSQL, the `pg_dump`
1044
- utility is used. For MySQL, this file will contain the output of
1045
- `SHOW CREATE TABLE` for the various tables.
1046
-
1047
- Loading these schemas is simply a question of executing the SQL statements they
1048
- contain. By definition, this will create a perfect copy of the database's
1049
- structure. Using the `:sql` schema format will, however, prevent loading the
1050
- schema into a RDBMS other than the one used to create it.
1051
-
1052
- ### Schema Dumps and Source Control
1053
-
1054
- Because schema dumps are the authoritative source for your database schema, it
1055
- is strongly recommended that you check them into source control.
1056
-
1057
- Active Record and Referential Integrity
1058
- ---------------------------------------
1059
-
1060
- The Active Record way claims that intelligence belongs in your models, not in
1061
- the database. As such, features such as triggers or foreign key constraints,
1062
- which push some of that intelligence back into the database, are not heavily
1063
- used.
1064
-
1065
- Validations such as `validates :foreign_key, uniqueness: true` are one way in
1066
- which models can enforce data integrity. The `:dependent` option on
1067
- associations allows models to automatically destroy child objects when the
1068
- parent is destroyed. Like anything which operates at the application level,
1069
- these cannot guarantee referential integrity and so some people augment them
1070
- with foreign key constraints in the database.
1071
-
1072
- Although Active Record does not provide any tools for working directly with
1073
- such features, the `execute` method can be used to execute arbitrary SQL. You
1074
- can also use a gem like
1075
- [foreigner](https://github.com/matthuhiggins/foreigner) which adds foreign key
1076
- support to Active Record (including support for dumping foreign keys in
1077
- `db/schema.rb`).
1078
-
1079
- Migrations and Seed Data
1080
- ------------------------
1081
-
1082
- Some people use migrations to add data to the database:
1083
-
1084
- ```ruby
1085
- class AddInitialProducts < ActiveRecord::Migration
1086
- def up
1087
- 5.times do |i|
1088
- Product.create(name: "Product ##{i}", description: "A product.")
1089
- end
1090
- end
1091
-
1092
- def down
1093
- Product.delete_all
1094
- end
1095
- end
1096
- ```
1097
-
1098
- However, Rails has a 'seeds' feature that should be used for seeding a database
1099
- with initial data. It's a really simple feature: just fill up `db/seeds.rb`
1100
- with some Ruby code, and run `rake db:seed`:
1101
-
1102
- ```ruby
1103
- 5.times do |i|
1104
- Product.create(name: "Product ##{i}", description: "A product.")
1105
- end
1106
- ```
1107
-
1108
- This is generally a much cleaner way to set up the database of a blank
1109
- application.