railties 3.0.11 → 3.0.12.rc1
Sign up to get free protection for your applications and to get access to all the features.
- data/lib/rails/version.rb +2 -2
- metadata +305 -461
- data/guides/output/2_2_release_notes.html +0 -565
- data/guides/output/2_3_release_notes.html +0 -713
- data/guides/output/3_0_release_notes.html +0 -652
- data/guides/output/3_1_release_notes.html +0 -670
- data/guides/output/action_controller_overview.html +0 -925
- data/guides/output/action_mailer_basics.html +0 -658
- data/guides/output/action_view_overview.html +0 -1471
- data/guides/output/active_model_basics.html +0 -349
- data/guides/output/active_record_basics.html +0 -364
- data/guides/output/active_record_querying.html +0 -1272
- data/guides/output/active_record_validations_callbacks.html +0 -1292
- data/guides/output/active_resource_basics.html +0 -252
- data/guides/output/active_support_core_extensions.html +0 -3374
- data/guides/output/ajax_on_rails.html +0 -412
- data/guides/output/api_documentation_guidelines.html +0 -317
- data/guides/output/asset_pipeline.html +0 -691
- data/guides/output/association_basics.html +0 -1742
- data/guides/output/caching_with_rails.html +0 -533
- data/guides/output/command_line.html +0 -662
- data/guides/output/configuring.html +0 -811
- data/guides/output/contribute.html +0 -216
- data/guides/output/contributing_to_ruby_on_rails.html +0 -465
- data/guides/output/credits.html +0 -210
- data/guides/output/debugging_rails_applications.html +0 -791
- data/guides/output/engines.html +0 -673
- data/guides/output/form_helpers.html +0 -850
- data/guides/output/generators.html +0 -725
- data/guides/output/getting_started.html +0 -1980
- data/guides/output/i18n.html +0 -1054
- data/guides/output/images/belongs_to.png +0 -0
- data/guides/output/images/book_icon.gif +0 -0
- data/guides/output/images/bullet.gif +0 -0
- data/guides/output/images/challenge.png +0 -0
- data/guides/output/images/chapters_icon.gif +0 -0
- data/guides/output/images/check_bullet.gif +0 -0
- data/guides/output/images/credits_pic_blank.gif +0 -0
- data/guides/output/images/csrf.png +0 -0
- data/guides/output/images/customized_error_messages.png +0 -0
- data/guides/output/images/edge_badge.png +0 -0
- data/guides/output/images/error_messages.png +0 -0
- data/guides/output/images/feature_tile.gif +0 -0
- data/guides/output/images/footer_tile.gif +0 -0
- data/guides/output/images/fxn.png +0 -0
- data/guides/output/images/grey_bullet.gif +0 -0
- data/guides/output/images/habtm.png +0 -0
- data/guides/output/images/has_many.png +0 -0
- data/guides/output/images/has_many_through.png +0 -0
- data/guides/output/images/has_one.png +0 -0
- data/guides/output/images/has_one_through.png +0 -0
- data/guides/output/images/header_backdrop.png +0 -0
- data/guides/output/images/header_tile.gif +0 -0
- data/guides/output/images/i18n/demo_html_safe.png +0 -0
- data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/output/images/i18n/demo_translated_en.png +0 -0
- data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/output/images/i18n/demo_translation_missing.png +0 -0
- data/guides/output/images/i18n/demo_untranslated.png +0 -0
- data/guides/output/images/icons/README +0 -5
- data/guides/output/images/icons/callouts/1.png +0 -0
- data/guides/output/images/icons/callouts/10.png +0 -0
- data/guides/output/images/icons/callouts/11.png +0 -0
- data/guides/output/images/icons/callouts/12.png +0 -0
- data/guides/output/images/icons/callouts/13.png +0 -0
- data/guides/output/images/icons/callouts/14.png +0 -0
- data/guides/output/images/icons/callouts/15.png +0 -0
- data/guides/output/images/icons/callouts/2.png +0 -0
- data/guides/output/images/icons/callouts/3.png +0 -0
- data/guides/output/images/icons/callouts/4.png +0 -0
- data/guides/output/images/icons/callouts/5.png +0 -0
- data/guides/output/images/icons/callouts/6.png +0 -0
- data/guides/output/images/icons/callouts/7.png +0 -0
- data/guides/output/images/icons/callouts/8.png +0 -0
- data/guides/output/images/icons/callouts/9.png +0 -0
- data/guides/output/images/icons/caution.png +0 -0
- data/guides/output/images/icons/example.png +0 -0
- data/guides/output/images/icons/home.png +0 -0
- data/guides/output/images/icons/important.png +0 -0
- data/guides/output/images/icons/next.png +0 -0
- data/guides/output/images/icons/note.png +0 -0
- data/guides/output/images/icons/prev.png +0 -0
- data/guides/output/images/icons/tip.png +0 -0
- data/guides/output/images/icons/up.png +0 -0
- data/guides/output/images/icons/warning.png +0 -0
- data/guides/output/images/jaimeiniesta.jpg +0 -0
- data/guides/output/images/nav_arrow.gif +0 -0
- data/guides/output/images/polymorphic.png +0 -0
- data/guides/output/images/posts_index.png +0 -0
- data/guides/output/images/radar.png +0 -0
- data/guides/output/images/rails_guides_logo.gif +0 -0
- data/guides/output/images/rails_logo_remix.gif +0 -0
- data/guides/output/images/rails_welcome.png +0 -0
- data/guides/output/images/session_fixation.png +0 -0
- data/guides/output/images/tab_grey.gif +0 -0
- data/guides/output/images/tab_info.gif +0 -0
- data/guides/output/images/tab_note.gif +0 -0
- data/guides/output/images/tab_red.gif +0 -0
- data/guides/output/images/tab_yellow.gif +0 -0
- data/guides/output/images/tab_yellow.png +0 -0
- data/guides/output/images/validation_error_messages.png +0 -0
- data/guides/output/images/vijaydev.jpg +0 -0
- data/guides/output/index.html +0 -300
- data/guides/output/initialization.html +0 -1087
- data/guides/output/javascripts/guides.js +0 -7
- data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
- data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
- data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
- data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
- data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
- data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
- data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
- data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
- data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
- data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
- data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
- data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
- data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
- data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
- data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
- data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
- data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
- data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
- data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
- data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
- data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
- data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
- data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
- data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
- data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
- data/guides/output/javascripts/syntaxhighlighter/shCore.js +0 -17
- data/guides/output/layout.html +0 -312
- data/guides/output/layouts_and_rendering.html +0 -1257
- data/guides/output/migrations.html +0 -751
- data/guides/output/nested_model_forms.html +0 -350
- data/guides/output/performance_testing.html +0 -858
- data/guides/output/plugins.html +0 -590
- data/guides/output/rails_application_templates.html +0 -368
- data/guides/output/rails_on_rack.html +0 -408
- data/guides/output/routing.html +0 -1246
- data/guides/output/ruby_on_rails_guides_guidelines.html +0 -218
- data/guides/output/security.html +0 -968
- data/guides/output/stylesheets/fixes.css +0 -16
- data/guides/output/stylesheets/main.css +0 -445
- data/guides/output/stylesheets/print.css +0 -52
- data/guides/output/stylesheets/reset.css +0 -43
- data/guides/output/stylesheets/style.css +0 -13
- data/guides/output/stylesheets/syntaxhighlighter/shCore.css +0 -226
- data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
- data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
- data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
- data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
- data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
- data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
- data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
- data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
- data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
- data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
- data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
- data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
- data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
- data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
- data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
- data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
- data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
- data/guides/output/testing.html +0 -1182
@@ -1,751 +0,0 @@
|
|
1
|
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
|
2
|
-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
3
|
-
|
4
|
-
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
5
|
-
<head>
|
6
|
-
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
7
|
-
|
8
|
-
<title>Ruby on Rails Guides: Migrations</title>
|
9
|
-
|
10
|
-
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
|
11
|
-
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
|
12
|
-
|
13
|
-
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
|
14
|
-
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
|
15
|
-
|
16
|
-
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
|
17
|
-
</head>
|
18
|
-
<body class="guide">
|
19
|
-
<div id="topNav">
|
20
|
-
<div class="wrapper">
|
21
|
-
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
|
22
|
-
<a href="http://rubyonrails.org/">Overview</a> |
|
23
|
-
<a href="http://rubyonrails.org/download">Download</a> |
|
24
|
-
<a href="http://rubyonrails.org/deploy">Deploy</a> |
|
25
|
-
<a href="https://github.com/rails/rails">Code</a> |
|
26
|
-
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
|
27
|
-
<a href="http://rubyonrails.org/documentation">Documentation</a> |
|
28
|
-
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
|
29
|
-
<a href="http://rubyonrails.org/community">Community</a> |
|
30
|
-
<a href="http://weblog.rubyonrails.org/">Blog</a>
|
31
|
-
</div>
|
32
|
-
</div>
|
33
|
-
<div id="header">
|
34
|
-
<div class="wrapper clearfix">
|
35
|
-
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
|
36
|
-
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
|
37
|
-
<ul class="nav">
|
38
|
-
<li><a href="index.html">Home</a></li>
|
39
|
-
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a>
|
40
|
-
<div id="guides" class="clearfix" style="display: none;">
|
41
|
-
<hr />
|
42
|
-
<dl class="L">
|
43
|
-
<dt>Start Here</dt>
|
44
|
-
<dd><a href="getting_started.html">Getting Started with Rails</a></dd>
|
45
|
-
<dt>Models</dt>
|
46
|
-
<dd><a href="migrations.html">Rails Database Migrations</a></dd>
|
47
|
-
<dd><a href="active_record_validations_callbacks.html">Active Record Validations and Callbacks</a></dd>
|
48
|
-
<dd><a href="association_basics.html">Active Record Associations</a></dd>
|
49
|
-
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
|
50
|
-
<dt>Views</dt>
|
51
|
-
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
|
52
|
-
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
|
53
|
-
<dt>Controllers</dt>
|
54
|
-
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
|
55
|
-
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
|
56
|
-
</dl>
|
57
|
-
<dl class="R">
|
58
|
-
<dt>Digging Deeper</dt>
|
59
|
-
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
|
60
|
-
<dd><a href="i18n.html">Rails Internationalization API</a></dd>
|
61
|
-
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
|
62
|
-
<dd><a href="testing.html">Testing Rails Applications</a></dd>
|
63
|
-
<dd><a href="security.html">Securing Rails Applications</a></dd>
|
64
|
-
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
|
65
|
-
<dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd>
|
66
|
-
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
|
67
|
-
<dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
|
68
|
-
<dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
|
69
|
-
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
|
70
|
-
|
71
|
-
<dt>Extending Rails</dt>
|
72
|
-
<dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
|
73
|
-
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
|
74
|
-
<dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
|
75
|
-
|
76
|
-
<dt>Contributing to Ruby on Rails</dt>
|
77
|
-
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
|
78
|
-
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
|
79
|
-
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
|
80
|
-
|
81
|
-
<dt>Release Notes</dt>
|
82
|
-
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
|
83
|
-
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
|
84
|
-
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
|
85
|
-
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
|
86
|
-
</dl>
|
87
|
-
</div>
|
88
|
-
</li>
|
89
|
-
<li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
|
90
|
-
<li><a href="credits.html">Credits</a></li>
|
91
|
-
</ul>
|
92
|
-
</div>
|
93
|
-
</div>
|
94
|
-
<hr class="hide" />
|
95
|
-
|
96
|
-
<div id="feature">
|
97
|
-
<div class="wrapper">
|
98
|
-
<h2>Migrations</h2>
|
99
|
-
<p>Migrations are a convenient way for you to alter your database in a structured and organized manner. You could edit fragments of <span class="caps">SQL</span> by hand but you would then be responsible for telling other developers that they need to go and run them. You’d also have to keep track of which changes need to be run against the production machines next time you deploy.</p>
|
100
|
-
<p>Active Record tracks which migrations have already been run so all you have to do is update your source and run <tt>rake db:migrate</tt>. Active Record will work out which migrations should be run. It will also update your <tt>db/schema.rb</tt> file to match the structure of your database.</p>
|
101
|
-
<p>Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record’s functionality) it is database independent: you don’t need to worry about the precise syntax of <tt>CREATE TABLE</tt> any more than you worry about variations on <tt>SELECT *</tt> (you can drop down to raw <span class="caps">SQL</span> for database specific features). For example you could use SQLite3 in development, but MySQL in production.</p>
|
102
|
-
<p>You’ll learn all about migrations including:</p>
|
103
|
-
<ul>
|
104
|
-
<li>The generators you can use to create them</li>
|
105
|
-
<li>The methods Active Record provides to manipulate your database</li>
|
106
|
-
<li>The Rake tasks that manipulate them</li>
|
107
|
-
<li>How they relate to <tt>schema.rb</tt></li>
|
108
|
-
</ul>
|
109
|
-
|
110
|
-
<div id="subCol">
|
111
|
-
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
|
112
|
-
<ol class="chapters">
|
113
|
-
<li><a href="#anatomy-of-a-migration">Anatomy of a Migration</a><ul><li><a href="#migrations-are-classes">Migrations are Classes</a></li> <li><a href="#what-s-in-a-name">What’s in a Name</a></li> <li><a href="#changing-migrations">Changing Migrations</a></li> <li><a href="#supported-types">Supported Types</a></li></ul></li><li><a href="#creating-a-migration">Creating a Migration</a><ul><li><a href="#creating-a-model">Creating a Model</a></li> <li><a href="#creating-a-standalone-migration">Creating a Standalone Migration</a></li></ul></li><li><a href="#writing-a-migration">Writing a Migration</a><ul><li><a href="#creating-a-table">Creating a Table</a></li> <li><a href="#changing-tables">Changing Tables</a></li> <li><a href="#special-helpers">Special Helpers</a></li> <li><a href="#writing-your-change-method">Writing Your <tt>change</tt> Method</a></li> <li><a href="#writing-your-down-method">Writing Your <tt>down</tt> Method</a></li></ul></li><li><a href="#running-migrations">Running Migrations</a><ul><li><a href="#rolling-back">Rolling Back</a></li> <li><a href="#being-specific">Being Specific</a></li> <li><a href="#being-talkative">Being Talkative</a></li></ul></li><li><a href="#using-models-in-your-migrations">Using Models in Your Migrations</a></li><li><a href="#schema-dumping-and-you">Schema Dumping and You</a><ul><li><a href="#what-are-schema-files-for">What are Schema Files for?</a></li> <li><a href="#types-of-schema-dumps">Types of Schema Dumps</a></li> <li><a href="#schema-dumps-and-source-control">Schema Dumps and Source Control</a></li></ul></li><li><a href="#active-record-and-referential-integrity">Active Record and Referential Integrity</a></li></ol></div>
|
114
|
-
</div>
|
115
|
-
</div>
|
116
|
-
|
117
|
-
<div id="container">
|
118
|
-
<div class="wrapper">
|
119
|
-
<div id="mainCol">
|
120
|
-
<h3 id="anatomy-of-a-migration">1 Anatomy of a Migration</h3>
|
121
|
-
<p>Before we dive into the details of a migration, here are a few examples of the sorts of things you can do:</p>
|
122
|
-
<div class="code_container">
|
123
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
124
|
-
class CreateProducts < ActiveRecord::Migration
|
125
|
-
def up
|
126
|
-
create_table :products do |t|
|
127
|
-
t.string :name
|
128
|
-
t.text :description
|
129
|
-
|
130
|
-
t.timestamps
|
131
|
-
end
|
132
|
-
end
|
133
|
-
|
134
|
-
def down
|
135
|
-
drop_table :products
|
136
|
-
end
|
137
|
-
end
|
138
|
-
</pre>
|
139
|
-
</div>
|
140
|
-
<p>This migration adds a table called <tt>products</tt> with a string column called <tt>name</tt> and a text column called <tt>description</tt>. A primary key column called <tt>id</tt> will also be added, however since this is the default we do not need to ask for this. The timestamp columns <tt>created_at</tt> and <tt>updated_at</tt> which Active Record populates automatically will also be added. Reversing this migration is as simple as dropping the table.</p>
|
141
|
-
<p>Migrations are not limited to changing the schema. You can also use them to fix bad data in the database or populate new fields:</p>
|
142
|
-
<div class="code_container">
|
143
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
144
|
-
class AddReceiveNewsletterToUsers < ActiveRecord::Migration
|
145
|
-
def up
|
146
|
-
change_table :users do |t|
|
147
|
-
t.boolean :receive_newsletter, :default => false
|
148
|
-
end
|
149
|
-
User.update_all ["receive_newsletter = ?", true]
|
150
|
-
end
|
151
|
-
|
152
|
-
def down
|
153
|
-
remove_column :users, :receive_newsletter
|
154
|
-
end
|
155
|
-
end
|
156
|
-
</pre>
|
157
|
-
</div>
|
158
|
-
<div class="note"><p>Some <a href="#using-models-in-your-migrations">caveats</a> apply to using models in your migrations.</p></div>
|
159
|
-
<p>This migration adds a <tt>receive_newsletter</tt> column to the <tt>users</tt> table. We want it to default to <tt>false</tt> for new users, but existing users are considered
|
160
|
-
to have already opted in, so we use the User model to set the flag to <tt>true</tt> for existing users.</p>
|
161
|
-
<p>Rails 3.1 makes migrations smarter by providing a new <tt>change</tt> method. This method is preferred for writing constructive migrations (adding columns or tables). The migration knows how to migrate your database and reverse it when the migration is rolled back without the need to write a separate <tt>down</tt> method.</p>
|
162
|
-
<div class="code_container">
|
163
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
164
|
-
class CreateProducts < ActiveRecord::Migration
|
165
|
-
def change
|
166
|
-
create_table :products do |t|
|
167
|
-
t.string :name
|
168
|
-
t.text :description
|
169
|
-
|
170
|
-
t.timestamps
|
171
|
-
end
|
172
|
-
end
|
173
|
-
end
|
174
|
-
</pre>
|
175
|
-
</div>
|
176
|
-
<h4 id="migrations-are-classes">1.1 Migrations are Classes</h4>
|
177
|
-
<p>A migration is a subclass of <tt>ActiveRecord::Migration</tt> that implements two methods: <tt>up</tt> (perform the required transformations) and <tt>down</tt> (revert them).</p>
|
178
|
-
<p>Active Record provides methods that perform common data definition tasks in a database independent way (you’ll read about them in detail later):</p>
|
179
|
-
<ul>
|
180
|
-
<li><tt>create_table</tt></li>
|
181
|
-
<li><tt>change_table</tt></li>
|
182
|
-
<li><tt>drop_table</tt></li>
|
183
|
-
<li><tt>add_column</tt></li>
|
184
|
-
<li><tt>change_column</tt></li>
|
185
|
-
<li><tt>rename_column</tt></li>
|
186
|
-
<li><tt>remove_column</tt></li>
|
187
|
-
<li><tt>add_index</tt></li>
|
188
|
-
<li><tt>remove_index</tt></li>
|
189
|
-
</ul>
|
190
|
-
<p>If you need to perform tasks specific to your database (for example create a <a href="#active-record-and-referential-integrity">foreign key</a> constraint) then the <tt>execute</tt> method allows you to execute arbitrary <span class="caps">SQL</span>. A migration is just a regular Ruby class so you’re not limited to these functions. For example after adding a column you could write code to set the value of that column for existing records (if necessary using your models).</p>
|
191
|
-
<p>On databases that support transactions with statements that change the schema (such as PostgreSQL or SQLite3), migrations are wrapped in a transaction. If the database does not support this (for example MySQL) then when a migration fails the parts of it that succeeded will not be rolled back. You will have to unpick the changes that were made by hand.</p>
|
192
|
-
<h4 id="what-s-in-a-name">1.2 What’s in a Name</h4>
|
193
|
-
<p>Migrations are stored in files in <tt>db/migrate</tt>, one for each migration class. The name of the file is of the form <tt>YYYYMMDDHHMMSS_create_products.rb</tt>, that is to say a <span class="caps">UTC</span> timestamp identifying the migration followed by an underscore followed by the name of the migration. The name of the migration class (CamelCased version) should match the latter part of the file name. For example <tt>20080906120000_create_products.rb</tt> should define class <tt>CreateProducts</tt> and <tt>20080906120001_add_details_to_products.rb</tt> should define <tt>AddDetailsToProducts</tt>. If you do feel the need to change the file name then you <em>have to</em> update the name of the class inside or Rails will complain about a missing class.</p>
|
194
|
-
<p>Internally Rails only uses the migration’s number (the timestamp) to identify them. Prior to Rails 2.1 the migration number started at 1 and was incremented each time a migration was generated. With multiple developers it was easy for these to clash requiring you to rollback migrations and renumber them. With Rails 2.1 this is largely avoided by using the creation time of the migration to identify them. You can revert to the old numbering scheme by adding the following line to <tt>config/application.rb</tt>.</p>
|
195
|
-
<div class="code_container">
|
196
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
197
|
-
config.active_record.timestamped_migrations = false
|
198
|
-
</pre>
|
199
|
-
</div>
|
200
|
-
<p>The combination of timestamps and recording which migrations have been run allows Rails to handle common situations that occur with multiple developers.</p>
|
201
|
-
<p>For example Alice adds migrations <tt>20080906120000</tt> and <tt>20080906123000</tt> and Bob adds <tt>20080906124500</tt> and runs it. Alice finishes her changes and checks in her migrations and Bob pulls down the latest changes. Rails knows that it has not run Alice’s two migrations so <tt>rake db:migrate</tt> would run them (even though Bob’s migration with a later timestamp has been run), and similarly migrating down would not run their <tt>down</tt> methods.</p>
|
202
|
-
<p>Of course this is no substitution for communication within the team. For example, if Alice’s migration removed a table that Bob’s migration assumed to exist, then trouble would certainly strike.</p>
|
203
|
-
<h4 id="changing-migrations">1.3 Changing Migrations</h4>
|
204
|
-
<p>Occasionally you will make a mistake when writing a migration. If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run <tt>rake db:migrate</tt>. You must rollback the migration (for example with <tt>rake db:rollback</tt>), edit your migration and then run <tt>rake db:migrate</tt> to run the corrected version.</p>
|
205
|
-
<p>In general editing existing migrations is not a good idea: you will be creating extra work for yourself and your co-workers and cause major headaches if the existing version of the migration has already been run on production machines. Instead, you should write a new migration that performs the changes you require. Editing a freshly generated migration that has not yet been committed to source control (or, more generally, which has not been propagated beyond your development machine) is relatively harmless.</p>
|
206
|
-
<h4 id="supported-types">1.4 Supported Types</h4>
|
207
|
-
<p>Active Record supports the following types:</p>
|
208
|
-
<ul>
|
209
|
-
<li><tt>:primary_key</tt></li>
|
210
|
-
<li><tt>:string</tt></li>
|
211
|
-
<li><tt>:text</tt></li>
|
212
|
-
<li><tt>:integer</tt></li>
|
213
|
-
<li><tt>:float</tt></li>
|
214
|
-
<li><tt>:decimal</tt></li>
|
215
|
-
<li><tt>:datetime</tt></li>
|
216
|
-
<li><tt>:timestamp</tt></li>
|
217
|
-
<li><tt>:time</tt></li>
|
218
|
-
<li><tt>:date</tt></li>
|
219
|
-
<li><tt>:binary</tt></li>
|
220
|
-
<li><tt>:boolean</tt></li>
|
221
|
-
</ul>
|
222
|
-
<p>These will be mapped onto an appropriate underlying database type. For example, with MySQL the type <tt>:string</tt> is mapped to <tt>VARCHAR(255)</tt>. You can create columns of types not supported by Active Record when using the non-sexy syntax, for example</p>
|
223
|
-
<div class="code_container">
|
224
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
225
|
-
create_table :products do |t|
|
226
|
-
t.column :name, 'polygon', :null => false
|
227
|
-
end
|
228
|
-
</pre>
|
229
|
-
</div>
|
230
|
-
<p>This may however hinder portability to other databases.</p>
|
231
|
-
<h3 id="creating-a-migration">2 Creating a Migration</h3>
|
232
|
-
<h4 id="creating-a-model">2.1 Creating a Model</h4>
|
233
|
-
<p>The model and scaffold generators will create migrations appropriate for adding a new model. This migration will already contain instructions for creating the relevant table. If you tell Rails what columns you want, then statements for adding these columns will also be created. For example, running</p>
|
234
|
-
<div class="code_container">
|
235
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
236
|
-
$ rails generate model Product name:string description:text
|
237
|
-
</pre>
|
238
|
-
</div>
|
239
|
-
<p>will create a migration that looks like this</p>
|
240
|
-
<div class="code_container">
|
241
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
242
|
-
class CreateProducts < ActiveRecord::Migration
|
243
|
-
def change
|
244
|
-
create_table :products do |t|
|
245
|
-
t.string :name
|
246
|
-
t.text :description
|
247
|
-
|
248
|
-
t.timestamps
|
249
|
-
end
|
250
|
-
end
|
251
|
-
end
|
252
|
-
</pre>
|
253
|
-
</div>
|
254
|
-
<p>You can append as many column name/type pairs as you want. By default <tt>t.timestamps</tt> (which creates the <tt>updated_at</tt> and <tt>created_at</tt> columns that
|
255
|
-
are automatically populated by Active Record) will be added for you.</p>
|
256
|
-
<h4 id="creating-a-standalone-migration">2.2 Creating a Standalone Migration</h4>
|
257
|
-
<p>If you are creating migrations for other purposes (for example to add a column to an existing table) then you can use the migration generator:</p>
|
258
|
-
<div class="code_container">
|
259
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
260
|
-
$ rails generate migration AddPartNumberToProducts
|
261
|
-
</pre>
|
262
|
-
</div>
|
263
|
-
<p>This will create an empty but appropriately named migration:</p>
|
264
|
-
<div class="code_container">
|
265
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
266
|
-
class AddPartNumberToProducts < ActiveRecord::Migration
|
267
|
-
def change
|
268
|
-
end
|
269
|
-
end
|
270
|
-
</pre>
|
271
|
-
</div>
|
272
|
-
<p>If the migration name is of the form “AddXXXToYYY” or “RemoveXXXFromYYY” and is followed by a list of column names and types then a migration containing the appropriate <tt>add_column</tt> and <tt>remove_column</tt> statements will be created.</p>
|
273
|
-
<div class="code_container">
|
274
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
275
|
-
$ rails generate migration AddPartNumberToProducts part_number:string
|
276
|
-
</pre>
|
277
|
-
</div>
|
278
|
-
<p>will generate</p>
|
279
|
-
<div class="code_container">
|
280
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
281
|
-
class AddPartNumberToProducts < ActiveRecord::Migration
|
282
|
-
def change
|
283
|
-
add_column :products, :part_number, :string
|
284
|
-
end
|
285
|
-
end
|
286
|
-
</pre>
|
287
|
-
</div>
|
288
|
-
<p>Similarly,</p>
|
289
|
-
<div class="code_container">
|
290
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
291
|
-
$ rails generate migration RemovePartNumberFromProducts part_number:string
|
292
|
-
</pre>
|
293
|
-
</div>
|
294
|
-
<p>generates</p>
|
295
|
-
<div class="code_container">
|
296
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
297
|
-
class RemovePartNumberFromProducts < ActiveRecord::Migration
|
298
|
-
def up
|
299
|
-
remove_column :products, :part_number
|
300
|
-
end
|
301
|
-
|
302
|
-
def down
|
303
|
-
add_column :products, :part_number, :string
|
304
|
-
end
|
305
|
-
end
|
306
|
-
</pre>
|
307
|
-
</div>
|
308
|
-
<p>You are not limited to one magically generated column, for example</p>
|
309
|
-
<div class="code_container">
|
310
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
311
|
-
$ rails generate migration AddDetailsToProducts part_number:string price:decimal
|
312
|
-
</pre>
|
313
|
-
</div>
|
314
|
-
<p>generates</p>
|
315
|
-
<div class="code_container">
|
316
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
317
|
-
class AddDetailsToProducts < ActiveRecord::Migration
|
318
|
-
def change
|
319
|
-
add_column :products, :part_number, :string
|
320
|
-
add_column :products, :price, :decimal
|
321
|
-
end
|
322
|
-
end
|
323
|
-
</pre>
|
324
|
-
</div>
|
325
|
-
<p>As always, what has been generated for you is just a starting point. You can add or remove from it as you see fit.</p>
|
326
|
-
<div class="note"><p>The generated migration file for destructive migrations will still be old-style using the <tt>up</tt> and <tt>down</tt> methods. This is because Rails doesn’t know the original data types defined when you made the original changes.</p></div>
|
327
|
-
<h3 id="writing-a-migration">3 Writing a Migration</h3>
|
328
|
-
<p>Once you have created your migration using one of the generators it’s time to get to work!</p>
|
329
|
-
<h4 id="creating-a-table">3.1 Creating a Table</h4>
|
330
|
-
<p>Migration method <tt>create_table</tt> will be one of your workhorses. A typical use would be</p>
|
331
|
-
<div class="code_container">
|
332
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
333
|
-
create_table :products do |t|
|
334
|
-
t.string :name
|
335
|
-
end
|
336
|
-
</pre>
|
337
|
-
</div>
|
338
|
-
<p>which creates a <tt>products</tt> table with a column called <tt>name</tt> (and as discussed below, an implicit <tt>id</tt> column).</p>
|
339
|
-
<p>The object yielded to the block allows you to create columns on the table. There are two ways of doing it. The first (traditional) form looks like</p>
|
340
|
-
<div class="code_container">
|
341
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
342
|
-
create_table :products do |t|
|
343
|
-
t.column :name, :string, :null => false
|
344
|
-
end
|
345
|
-
</pre>
|
346
|
-
</div>
|
347
|
-
<p>The second form, the so called “sexy” migration, drops the somewhat redundant <tt>column</tt> method. Instead, the <tt>string</tt>, <tt>integer</tt>, etc. methods create a column of that type. Subsequent parameters are the same.</p>
|
348
|
-
<div class="code_container">
|
349
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
350
|
-
create_table :products do |t|
|
351
|
-
t.string :name, :null => false
|
352
|
-
end
|
353
|
-
</pre>
|
354
|
-
</div>
|
355
|
-
<p>By default, <tt>create_table</tt> will create a primary key called <tt>id</tt>. You can change the name of the primary key with the <tt>:primary_key</tt> option (don’t forget to update the corresponding model) or, if you don’t want a primary key at all (for example for a <span class="caps">HABTM</span> join table), you can pass the option <tt>:id => false</tt>. If you need to pass database specific options you can place an <span class="caps">SQL</span> fragment in the <tt>:options</tt> option. For example,</p>
|
356
|
-
<div class="code_container">
|
357
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
358
|
-
create_table :products, :options => "ENGINE=BLACKHOLE" do |t|
|
359
|
-
t.string :name, :null => false
|
360
|
-
end
|
361
|
-
</pre>
|
362
|
-
</div>
|
363
|
-
<p>will append <tt>ENGINE=BLACKHOLE</tt> to the <span class="caps">SQL</span> statement used to create the table (when using MySQL, the default is <tt>ENGINE=InnoDB</tt>).</p>
|
364
|
-
<h4 id="changing-tables">3.2 Changing Tables</h4>
|
365
|
-
<p>A close cousin of <tt>create_table</tt> is <tt>change_table</tt>, used for changing existing tables. It is used in a similar fashion to <tt>create_table</tt> but the object yielded to the block knows more tricks. For example</p>
|
366
|
-
<div class="code_container">
|
367
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
368
|
-
change_table :products do |t|
|
369
|
-
t.remove :description, :name
|
370
|
-
t.string :part_number
|
371
|
-
t.index :part_number
|
372
|
-
t.rename :upccode, :upc_code
|
373
|
-
end
|
374
|
-
</pre>
|
375
|
-
</div>
|
376
|
-
<p>removes the <tt>description</tt> and <tt>name</tt> columns, creates a <tt>part_number</tt> column and adds an index on it. Finally it renames the <tt>upccode</tt> column. This is the same as doing</p>
|
377
|
-
<div class="code_container">
|
378
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
379
|
-
remove_column :products, :description
|
380
|
-
remove_column :products, :name
|
381
|
-
add_column :products, :part_number, :string
|
382
|
-
add_index :products, :part_number
|
383
|
-
rename_column :products, :upccode, :upc_code
|
384
|
-
</pre>
|
385
|
-
</div>
|
386
|
-
<p>You don’t have to keep repeating the table name and it groups all the statements related to modifying one particular table. The individual transformation names are also shorter, for example <tt>remove_column</tt> becomes just <tt>remove</tt> and <tt>add_index</tt> becomes just <tt>index</tt>.</p>
|
387
|
-
<h4 id="special-helpers">3.3 Special Helpers</h4>
|
388
|
-
<p>Active Record provides some shortcuts for common functionality. It is for example very common to add both the <tt>created_at</tt> and <tt>updated_at</tt> columns and so there is a method that does exactly that:</p>
|
389
|
-
<div class="code_container">
|
390
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
391
|
-
create_table :products do |t|
|
392
|
-
t.timestamps
|
393
|
-
end
|
394
|
-
</pre>
|
395
|
-
</div>
|
396
|
-
<p>will create a new products table with those two columns (plus the <tt>id</tt> column) whereas</p>
|
397
|
-
<div class="code_container">
|
398
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
399
|
-
change_table :products do |t|
|
400
|
-
t.timestamps
|
401
|
-
end
|
402
|
-
</pre>
|
403
|
-
</div>
|
404
|
-
<p>adds those columns to an existing table.</p>
|
405
|
-
<p>The other helper is called <tt>references</tt> (also available as <tt>belongs_to</tt>). In its simplest form it just adds some readability</p>
|
406
|
-
<div class="code_container">
|
407
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
408
|
-
create_table :products do |t|
|
409
|
-
t.references :category
|
410
|
-
end
|
411
|
-
</pre>
|
412
|
-
</div>
|
413
|
-
<p>will create a <tt>category_id</tt> column of the appropriate type. Note that you pass the model name, not the column name. Active Record adds the <tt>_id</tt> for you. If you have polymorphic <tt>belongs_to</tt> associations then <tt>references</tt> will add both of the columns required:</p>
|
414
|
-
<div class="code_container">
|
415
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
416
|
-
create_table :products do |t|
|
417
|
-
t.references :attachment, :polymorphic => {:default => 'Photo'}
|
418
|
-
end
|
419
|
-
</pre>
|
420
|
-
</div>
|
421
|
-
<p>will add an <tt>attachment_id</tt> column and a string <tt>attachment_type</tt> column with a default value of ‘Photo’.</p>
|
422
|
-
<div class="note"><p>The <tt>references</tt> helper does not actually create foreign key constraints for you. You will need to use <tt>execute</tt> or a plugin that adds <a href="#active-record-and-referential-integrity">foreign key support</a>.</p></div>
|
423
|
-
<p>If the helpers provided by Active Record aren’t enough you can use the <tt>execute</tt> method to execute arbitrary <span class="caps">SQL</span>.</p>
|
424
|
-
<p>For more details and examples of individual methods, check the <span class="caps">API</span> documentation, in particular the documentation for <a href="http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html"><tt>ActiveRecord::ConnectionAdapters::SchemaStatements</tt></a> (which provides the methods available in the <tt>up</tt> and <tt>down</tt> methods), <a href="http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html"><tt>ActiveRecord::ConnectionAdapters::TableDefinition</tt></a> (which provides the methods available on the object yielded by <tt>create_table</tt>) and <a href="http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html"><tt>ActiveRecord::ConnectionAdapters::Table</tt></a> (which provides the methods available on the object yielded by <tt>change_table</tt>).</p>
|
425
|
-
<h4 id="writing-your-change-method">3.4 Writing Your <tt>change</tt> Method</h4>
|
426
|
-
<p>The <tt>change</tt> method removes the need to write both <tt>up</tt> and <tt>down</tt> methods in those cases that Rails know how to revert the changes automatically. Currently, the <tt>change</tt> method supports only these migration definitions:</p>
|
427
|
-
<ul>
|
428
|
-
<li><tt>add_column</tt></li>
|
429
|
-
<li><tt>add_index</tt></li>
|
430
|
-
<li><tt>add_timestamps</tt></li>
|
431
|
-
<li><tt>create_table</tt></li>
|
432
|
-
<li><tt>remove_timestamps</tt></li>
|
433
|
-
<li><tt>rename_column</tt></li>
|
434
|
-
<li><tt>rename_index</tt></li>
|
435
|
-
<li><tt>rename_table</tt></li>
|
436
|
-
</ul>
|
437
|
-
<p>If you’re going to use other methods, you’ll have to write the <tt>up</tt> and <tt>down</tt> methods normally.</p>
|
438
|
-
<h4 id="writing-your-down-method">3.5 Writing Your <tt>down</tt> Method</h4>
|
439
|
-
<p>The <tt>down</tt> method of your migration should revert the transformations done by the <tt>up</tt> method. In other words, the database schema should be unchanged if you do an <tt>up</tt> followed by a <tt>down</tt>. For example, if you create a table in the <tt>up</tt> method, you should drop it in the <tt>down</tt> method. It is wise to reverse the transformations in precisely the reverse order they were made in the <tt>up</tt> method. For example,</p>
|
440
|
-
<div class="code_container">
|
441
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
442
|
-
class ExampleMigration < ActiveRecord::Migration
|
443
|
-
|
444
|
-
def up
|
445
|
-
create_table :products do |t|
|
446
|
-
t.references :category
|
447
|
-
end
|
448
|
-
#add a foreign key
|
449
|
-
execute <<-SQL
|
450
|
-
ALTER TABLE products
|
451
|
-
ADD CONSTRAINT fk_products_categories
|
452
|
-
FOREIGN KEY (category_id)
|
453
|
-
REFERENCES categories(id)
|
454
|
-
SQL
|
455
|
-
|
456
|
-
add_column :users, :home_page_url, :string
|
457
|
-
|
458
|
-
rename_column :users, :email, :email_address
|
459
|
-
end
|
460
|
-
|
461
|
-
def down
|
462
|
-
rename_column :users, :email_address, :email
|
463
|
-
remove_column :users, :home_page_url
|
464
|
-
execute "ALTER TABLE products DROP FOREIGN KEY fk_products_categories"
|
465
|
-
drop_table :products
|
466
|
-
end
|
467
|
-
end
|
468
|
-
</pre>
|
469
|
-
</div>
|
470
|
-
<p>Sometimes your migration will do something which is just plain irreversible; for example, it might destroy some data. In such cases, you can raise <tt>ActiveRecord::IrreversibleMigration</tt> from your <tt>down</tt> method. If someone tries to revert your migration, an error message will be displayed saying that it can’t be done.</p>
|
471
|
-
<h3 id="running-migrations">4 Running Migrations</h3>
|
472
|
-
<p>Rails provides a set of rake tasks to work with migrations which boil down to running certain sets of migrations. The very first migration related rake task you will use will probably be <tt>db:migrate</tt>. In its most basic form it just runs the <tt>up</tt> method for all the migrations that have not yet been run. If there are no such migrations, it exits.</p>
|
473
|
-
<p>Note that running the <tt>db:migrate</tt> also invokes the <tt>db:schema:dump</tt> task, which will update your db/schema.rb file to match the structure of your database.</p>
|
474
|
-
<p>If you specify a target version, Active Record will run the required migrations (up or down) until it has reached the specified version. The
|
475
|
-
version is the numerical prefix on the migration’s filename. For example, to migrate to version 20080906120000 run</p>
|
476
|
-
<div class="code_container">
|
477
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
478
|
-
$ rake db:migrate VERSION=20080906120000
|
479
|
-
</pre>
|
480
|
-
</div>
|
481
|
-
<p>If version 20080906120000 is greater than the current version (i.e., it is migrating upwards), this will run the <tt>up</tt> method on all migrations up to and including 20080906120000. If migrating downwards, this will run the <tt>down</tt> method on all the migrations down to, but not including, 20080906120000.</p>
|
482
|
-
<h4 id="rolling-back">4.1 Rolling Back</h4>
|
483
|
-
<p>A common task is to rollback the last migration, for example if you made a mistake in it and wish to correct it. Rather than tracking down the version number associated with the previous migration you can run</p>
|
484
|
-
<div class="code_container">
|
485
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
486
|
-
$ rake db:rollback
|
487
|
-
</pre>
|
488
|
-
</div>
|
489
|
-
<p>This will run the <tt>down</tt> method from the latest migration. If you need to undo several migrations you can provide a <tt>STEP</tt> parameter:</p>
|
490
|
-
<div class="code_container">
|
491
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
492
|
-
$ rake db:rollback STEP=3
|
493
|
-
</pre>
|
494
|
-
</div>
|
495
|
-
<p>will run the <tt>down</tt> method from the last 3 migrations.</p>
|
496
|
-
<p>The <tt>db:migrate:redo</tt> task is a shortcut for doing a rollback and then migrating back up again. As with the <tt>db:rollback</tt> task, you can use the <tt>STEP</tt> parameter if you need to go more than one version back, for example</p>
|
497
|
-
<div class="code_container">
|
498
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
499
|
-
$ rake db:migrate:redo STEP=3
|
500
|
-
</pre>
|
501
|
-
</div>
|
502
|
-
<p>Neither of these Rake tasks do anything you could not do with <tt>db:migrate</tt>. They are simply more convenient, since you do not need to explicitly specify the version to migrate to.</p>
|
503
|
-
<p>Lastly, the <tt>db:reset</tt> task will drop the database, recreate it and load the current schema into it.</p>
|
504
|
-
<div class="note"><p>This is not the same as running all the migrations – see the section on <a href="#schema-dumping-and-you">schema.rb</a>.</p></div>
|
505
|
-
<h4 id="being-specific">4.2 Being Specific</h4>
|
506
|
-
<p>If you need to run a specific migration up or down, the <tt>db:migrate:up</tt> and <tt>db:migrate:down</tt> tasks will do that. Just specify the appropriate version and the corresponding migration will have its <tt>up</tt> or <tt>down</tt> method invoked, for example,</p>
|
507
|
-
<div class="code_container">
|
508
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
509
|
-
$ rake db:migrate:up VERSION=20080906120000
|
510
|
-
</pre>
|
511
|
-
</div>
|
512
|
-
<p>will run the <tt>up</tt> method from the 20080906120000 migration. These tasks check whether the migration has already run, so for example <tt>db:migrate:up VERSION=20080906120000</tt> will do nothing if Active Record believes that 20080906120000 has already been run.</p>
|
513
|
-
<h4 id="being-talkative">4.3 Being Talkative</h4>
|
514
|
-
<p>By default migrations tell you exactly what they’re doing and how long it took. A migration creating a table and adding an index might produce output like this</p>
|
515
|
-
<div class="code_container">
|
516
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
517
|
-
20080906170109 CreateProducts: migrating
|
518
|
-
-- create_table(:products)
|
519
|
-
-> 0.0021s
|
520
|
-
-- add_index(:products, :name)
|
521
|
-
-> 0.0026s
|
522
|
-
20080906170109 CreateProducts: migrated (0.0059s)
|
523
|
-
</pre>
|
524
|
-
</div>
|
525
|
-
<p>Several methods are provided that allow you to control all this:</p>
|
526
|
-
<ul>
|
527
|
-
<li><tt>suppress_messages</tt> takes a block as an argument and suppresses any output generated by the block.</li>
|
528
|
-
<li><tt>say</tt> takes a message argument and outputs it as is. A second boolean argument can be passed to specify whether to indent or not.</li>
|
529
|
-
<li><tt>say_with_time</tt> 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.</li>
|
530
|
-
</ul>
|
531
|
-
<p>For example, this migration</p>
|
532
|
-
<div class="code_container">
|
533
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
534
|
-
class CreateProducts < ActiveRecord::Migration
|
535
|
-
def change
|
536
|
-
suppress_messages do
|
537
|
-
create_table :products do |t|
|
538
|
-
t.string :name
|
539
|
-
t.text :description
|
540
|
-
t.timestamps
|
541
|
-
end
|
542
|
-
end
|
543
|
-
say "Created a table"
|
544
|
-
suppress_messages {add_index :products, :name}
|
545
|
-
say "and an index!", true
|
546
|
-
say_with_time 'Waiting for a while' do
|
547
|
-
sleep 10
|
548
|
-
250
|
549
|
-
end
|
550
|
-
end
|
551
|
-
end
|
552
|
-
</pre>
|
553
|
-
</div>
|
554
|
-
<p>generates the following output</p>
|
555
|
-
<div class="code_container">
|
556
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
557
|
-
20080906170109 CreateProducts: migrating
|
558
|
-
Created a table
|
559
|
-
-> and an index!
|
560
|
-
Waiting for a while
|
561
|
-
-> 10.0001s
|
562
|
-
-> 250 rows
|
563
|
-
20080906170109 CreateProducts: migrated (10.0097s)
|
564
|
-
</pre>
|
565
|
-
</div>
|
566
|
-
<p>If you just want Active Record to shut up, then running <tt>rake db:migrate VERBOSE=false</tt> will suppress all output.</p>
|
567
|
-
<h3 id="using-models-in-your-migrations">5 Using Models in Your Migrations</h3>
|
568
|
-
<p>When creating or updating data in a migration it is often tempting to use one of your models. After all, they exist to provide easy access to the underlying data. This can be done, but some caution should be observed.</p>
|
569
|
-
<p>For example, problems occur when the model uses database columns which are (1) not currently in the database and (2) will be created by this or a subsequent migration.</p>
|
570
|
-
<p>Consider this example, where Alice and Bob are working on the same code base which contains a <tt>Product</tt> model:</p>
|
571
|
-
<p>Bob goes on vacation.</p>
|
572
|
-
<p>Alice creates a migration for the <tt>products</tt> table which adds a new column and initializes it.
|
573
|
-
She also adds a validation to the <tt>Product</tt> model for the new column.</p>
|
574
|
-
<div class="code_container">
|
575
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
576
|
-
# db/migrate/20100513121110_add_flag_to_product.rb
|
577
|
-
|
578
|
-
class AddFlagToProduct < ActiveRecord::Migration
|
579
|
-
def change
|
580
|
-
add_column :products, :flag, :int
|
581
|
-
Product.all.each { |f| f.update_attributes!(:flag => 'false') }
|
582
|
-
end
|
583
|
-
end
|
584
|
-
</pre>
|
585
|
-
</div>
|
586
|
-
<div class="code_container">
|
587
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
588
|
-
# app/model/product.rb
|
589
|
-
|
590
|
-
class Product < ActiveRecord::Base
|
591
|
-
validates :flag, :presence => true
|
592
|
-
end
|
593
|
-
</pre>
|
594
|
-
</div>
|
595
|
-
<p>Alice adds a second migration which adds and initializes another column to the <tt>products</tt> table and also adds a validation to the <tt>Product</tt> model for the new column.</p>
|
596
|
-
<div class="code_container">
|
597
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
598
|
-
# db/migrate/20100515121110_add_fuzz_to_product.rb
|
599
|
-
|
600
|
-
class AddFuzzToProduct < ActiveRecord::Migration
|
601
|
-
def change
|
602
|
-
add_column :products, :fuzz, :string
|
603
|
-
Product.all.each { |f| f.update_attributes! :fuzz => 'fuzzy' }
|
604
|
-
end
|
605
|
-
end
|
606
|
-
</pre>
|
607
|
-
</div>
|
608
|
-
<div class="code_container">
|
609
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
610
|
-
# app/model/product.rb
|
611
|
-
|
612
|
-
class Product < ActiveRecord::Base
|
613
|
-
validates :flag, :fuzz, :presence => true
|
614
|
-
end
|
615
|
-
</pre>
|
616
|
-
</div>
|
617
|
-
<p>Both migrations work for Alice.</p>
|
618
|
-
<p>Bob comes back from vacation and:</p>
|
619
|
-
<ol>
|
620
|
-
<li>updates the source – which contains both migrations and the latests version of the Product model.</li>
|
621
|
-
<li>runs outstanding migrations with <tt>rake db:migrate</tt>, which includes the one that updates the <tt>Product</tt> model.</li>
|
622
|
-
</ol>
|
623
|
-
<p>The migration crashes because when the model attempts to save, it tries to validate the second added column, which is not in the database when the <em>first</em> migration runs:</p>
|
624
|
-
<div class="code_container">
|
625
|
-
<pre class="brush: plain; gutter: false; toolbar: false">
|
626
|
-
rake aborted!
|
627
|
-
An error has occurred, this and all later migrations canceled:
|
628
|
-
|
629
|
-
undefined method `fuzz' for #<Product:0x000001049b14a0>
|
630
|
-
</pre>
|
631
|
-
</div>
|
632
|
-
<p>A fix for this is to create a local model within the migration. This keeps rails from running the validations, so that the migrations run to completion.</p>
|
633
|
-
<p>When using a faux model, it’s a good idea to call <tt>Product.reset_column_information</tt> to refresh the <tt>ActiveRecord</tt> cache for the <tt>Product</tt> model prior to updating data in the database.</p>
|
634
|
-
<p>If Alice had done this instead, there would have been no problem:</p>
|
635
|
-
<div class="code_container">
|
636
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
637
|
-
# db/migrate/20100513121110_add_flag_to_product.rb
|
638
|
-
|
639
|
-
class AddFlagToProduct < ActiveRecord::Migration
|
640
|
-
class Product < ActiveRecord::Base
|
641
|
-
end
|
642
|
-
|
643
|
-
def change
|
644
|
-
add_column :products, :flag, :int
|
645
|
-
Product.reset_column_information
|
646
|
-
Product.all.each { |f| f.update_attributes!(:flag => false) }
|
647
|
-
end
|
648
|
-
end
|
649
|
-
</pre>
|
650
|
-
</div>
|
651
|
-
<div class="code_container">
|
652
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
653
|
-
# db/migrate/20100515121110_add_fuzz_to_product.rb
|
654
|
-
|
655
|
-
class AddFuzzToProduct < ActiveRecord::Migration
|
656
|
-
class Product < ActiveRecord::Base
|
657
|
-
end
|
658
|
-
def change
|
659
|
-
add_column :products, :fuzz, :string
|
660
|
-
Product.reset_column_information
|
661
|
-
Product.all.each { |f| f.update_attributes! :fuzz => 'fuzzy' }
|
662
|
-
end
|
663
|
-
end
|
664
|
-
</pre>
|
665
|
-
</div>
|
666
|
-
<h3 id="schema-dumping-and-you">6 Schema Dumping and You</h3>
|
667
|
-
<h4 id="what-are-schema-files-for">6.1 What are Schema Files for?</h4>
|
668
|
-
<p>Migrations, mighty as they may be, are not the authoritative source for your database schema. That role falls to either <tt>db/schema.rb</tt> or an <span class="caps">SQL</span> file which Active Record generates by examining the database. They are not designed to be edited, they just represent the current state of the database.</p>
|
669
|
-
<p>There is no need (and it is error prone) to deploy a new instance of an app by replaying the entire migration history. It is much simpler and faster to just load into the database a description of the current schema.</p>
|
670
|
-
<p>For example, this is how the test database is created: the current development database is dumped (either to <tt>db/schema.rb</tt> or <tt>db/development.sql</tt>) and then loaded into the test database.</p>
|
671
|
-
<p>Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model’s code and is frequently spread across several migrations, but is summed up in the schema file. The <a href="https://github.com/ctran/annotate_models">annotate_models</a> gem automatically adds and updates comments at the top of each model summarizing the schema if you desire that functionality.</p>
|
672
|
-
<h4 id="types-of-schema-dumps">6.2 Types of Schema Dumps</h4>
|
673
|
-
<p>There are two ways to dump the schema. This is set in <tt>config/application.rb</tt> by the <tt>config.active_record.schema_format</tt> setting, which may be either <tt>:sql</tt> or <tt>:ruby</tt>.</p>
|
674
|
-
<p>If <tt>:ruby</tt> is selected then the schema is stored in <tt>db/schema.rb</tt>. If you look at this file you’ll find that it looks an awful lot like one very big migration:</p>
|
675
|
-
<div class="code_container">
|
676
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
677
|
-
ActiveRecord::Schema.define(:version => 20080906171750) do
|
678
|
-
create_table "authors", :force => true do |t|
|
679
|
-
t.string "name"
|
680
|
-
t.datetime "created_at"
|
681
|
-
t.datetime "updated_at"
|
682
|
-
end
|
683
|
-
|
684
|
-
create_table "products", :force => true do |t|
|
685
|
-
t.string "name"
|
686
|
-
t.text "description"
|
687
|
-
t.datetime "created_at"
|
688
|
-
t.datetime "updated_at"
|
689
|
-
t.string "part_number"
|
690
|
-
end
|
691
|
-
end
|
692
|
-
</pre>
|
693
|
-
</div>
|
694
|
-
<p>In many ways this is exactly what it is. This file is created by inspecting the database and expressing its structure using <tt>create_table</tt>, <tt>add_index</tt>, and so on. Because this is database-independent, it could be loaded into any database that Active Record supports. This could be very useful if you were to distribute an application that is able to run against multiple databases.</p>
|
695
|
-
<p>There is however a trade-off: <tt>db/schema.rb</tt> cannot express database specific items such as foreign key constraints, triggers, or stored procedures. While in a migration you can execute custom <span class="caps">SQL</span> statements, the schema dumper cannot reconstitute those statements from the database. If you are using features like this, then you should set the schema format to <tt>:sql</tt>.</p>
|
696
|
-
<p>Instead of using Active Record’s schema dumper, the database’s structure will be dumped using a tool specific to the database (via the <tt>db:structure:dump</tt> Rake task) into <tt>db/#{Rails.env}_structure.sql</tt>. For example, for the PostgreSQL <span class="caps">RDBMS</span>, the <tt>pg_dump</tt> utility is used. For MySQL, this file will contain the output of <tt>SHOW CREATE TABLE</tt> for the various tables. Loading these schemas is simply a question of executing the <span class="caps">SQL</span> statements they contain. By definition, this will create a perfect copy of the database’s structure. Using the <tt>:sql</tt> schema format will, however, prevent loading the schema into a <span class="caps">RDBMS</span> other than the one used to create it.</p>
|
697
|
-
<h4 id="schema-dumps-and-source-control">6.3 Schema Dumps and Source Control</h4>
|
698
|
-
<p>Because schema dumps are the authoritative source for your database schema, it is strongly recommended that you check them into source control.</p>
|
699
|
-
<h3 id="active-record-and-referential-integrity">7 Active Record and Referential Integrity</h3>
|
700
|
-
<p>The Active Record way claims that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database, are not heavily used.</p>
|
701
|
-
<p>Validations such as <tt>validates :foreign_key, :uniqueness => true</tt> are one way in which models can enforce data integrity. The <tt>:dependent</tt> option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level, these cannot guarantee referential integrity and so some people augment them with foreign key constraints.</p>
|
702
|
-
<p>Although Active Record does not provide any tools for working directly with such features, the <tt>execute</tt> method can be used to execute arbitrary <span class="caps">SQL</span>. There are also a number of plugins such as <a href="https://github.com/harukizaemon/redhillonrails/tree/master/foreign_key_migrations/">foreign_key_migrations</a> which add foreign key support to Active Record (including support for dumping foreign keys in <tt>db/schema.rb</tt>).</p>
|
703
|
-
|
704
|
-
<h3>Feedback</h3>
|
705
|
-
<p>
|
706
|
-
You're encouraged to help improve the quality of this guide.
|
707
|
-
</p>
|
708
|
-
<p>
|
709
|
-
If you see any typos or factual errors you are confident to
|
710
|
-
patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
|
711
|
-
and push the change yourself. That branch of Rails has public write access.
|
712
|
-
Commits are still reviewed, but that happens after you've submitted your
|
713
|
-
contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
|
714
|
-
cross-merged with master periodically.
|
715
|
-
</p>
|
716
|
-
<p>
|
717
|
-
You may also find incomplete content, or stuff that is not up to date.
|
718
|
-
Please do add any missing documentation for master. Check the
|
719
|
-
<a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
|
720
|
-
for style and conventions.
|
721
|
-
</p>
|
722
|
-
<p>
|
723
|
-
If for whatever reason you spot something to fix but cannot patch it yourself, please
|
724
|
-
<a href="https://github.com/rails/rails/issues">open an issue</a>.
|
725
|
-
</p>
|
726
|
-
<p>And last but not least, any kind of discussion regarding Ruby on Rails
|
727
|
-
documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
|
728
|
-
</p>
|
729
|
-
</div>
|
730
|
-
</div>
|
731
|
-
</div>
|
732
|
-
|
733
|
-
<hr class="hide" />
|
734
|
-
<div id="footer">
|
735
|
-
<div class="wrapper">
|
736
|
-
<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
|
737
|
-
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
|
738
|
-
</div>
|
739
|
-
</div>
|
740
|
-
|
741
|
-
<script type="text/javascript" src="javascripts/guides.js"></script>
|
742
|
-
<script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
|
743
|
-
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
|
744
|
-
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
|
745
|
-
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
|
746
|
-
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
|
747
|
-
<script type="text/javascript">
|
748
|
-
SyntaxHighlighter.all()
|
749
|
-
</script>
|
750
|
-
</body>
|
751
|
-
</html>
|