Froze rails gems
[depot.git] / vendor / rails / railties / doc / guides / html / migrations.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
5 <title>Migrations</title>
6 <!--[if lt IE 8]>
7 <script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
8 <![endif]-->
9 <link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
10 <link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
11 <link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
12 <style type="text/css">
13 div#container {
14 max-width: 900px;
15 padding-bottom: 3em;
16 }
17
18 div#content {
19 margin-left: 200px;
20 }
21
22 div#container.notoc {
23 max-width: 600px;
24 }
25
26 .notoc div#content {
27 margin-left: 0;
28 }
29
30 pre {
31 line-height: 1.4em;
32 }
33
34 #content p tt {
35 background: #eeeeee;
36 border: solid 1px #cccccc;
37 padding: 3px;
38 }
39
40 dt {
41 font-weight: bold;
42 }
43
44 #content dt tt {
45 font-size: 10pt;
46 }
47
48 dd {
49 margin-left: 3em;
50 }
51
52 #content dt tt, #content pre tt {
53 background: none;
54 padding: 0;
55 border: 0;
56 }
57
58 #content .olist ol {
59 margin-left: 2em;
60 }
61
62 #header {
63 position: relative;
64 max-width: 840px;
65 margin-left: auto;
66 margin-right: auto;
67 }
68
69 #header.notoc {
70 max-width: 580px;
71 }
72
73 #logo {
74 position: absolute;
75 left: 10px;
76 top: 10px;
77 width: 110px;
78 height: 140px;
79 }
80
81 div#header h1#site_title {
82 background: url('images/ruby_on_rails_by_mike_rundle2.gif') top left no-repeat;
83 position: absolute;
84 width: 392px;
85 height: 55px;
86 left: 145px;
87 top: 20px;
88 margin: 0;
89 padding: 0;
90 }
91
92 #site_title span {
93 display: none;
94 }
95
96 #site_title_tagline {
97 display: none;
98 }
99
100 ul#navMain {
101 position: absolute;
102 margin: 0;
103 padding: 0;
104 top: 97px;
105 left: 145px;
106 }
107
108 .left-floaty, .right-floaty {
109 padding: 15px;
110 }
111
112 .admonitionblock,
113 .tableblock {
114 margin-left: 1em;
115 margin-right: 1em;
116 margin-top: 0.25em;
117 margin-bottom: 1em;
118 }
119
120 .admonitionblock .icon {
121 padding-right: 8px;
122 }
123
124 .admonitionblock .content {
125 border: solid 1px #ffda78;
126 background: #fffebd;
127 padding: 10px;
128 padding-top: 8px;
129 padding-bottom: 8px;
130 }
131
132 .admonitionblock .title {
133 font-size: 140%;
134 margin-bottom: 0.5em;
135 }
136
137 .tableblock table {
138 border: solid 1px #aaaaff;
139 background: #f0f0ff;
140 }
141
142 .tableblock th {
143 background: #e0e0e0;
144 }
145
146 .tableblock th,
147 .tableblock td {
148 padding: 3px;
149 padding-left: 5px;
150 padding-right: 5px;
151 }
152
153 .sidebarblock {
154 margin-top: 0.25em;
155 margin: 1em;
156 border: solid 1px #ccccbb;
157 padding: 8px;
158 background: #ffffe0;
159 }
160
161 .sidebarblock .sidebar-title {
162 font-size: 140%;
163 font-weight: 600;
164 margin-bottom: 0.3em;
165 }
166
167 .sidebarblock .sidebar-content > .para:last-child > p {
168 margin-bottom: 0;
169 }
170
171 .sidebarblock .sidebar-title a {
172 text-decoration: none;
173 }
174
175 .sidebarblock .sidebar-title a:hover {
176 text-decoration: underline;
177 }
178
179 </style>
180 </head>
181 <body>
182 <div id="header" >
183 <div id="logo">
184 <a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
185 </div>
186
187 <h1 id="site_title"><span>Ruby on Rails</span></h1>
188 <h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>
189
190 <ul id="navMain">
191 <li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
192 <li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
193 </ul>
194 </div>
195
196 <div id="container">
197
198 <div id="sidebar">
199 <h2>Chapters</h2>
200 <ol>
201 <li>
202 <a href="#_anatomy_of_a_migration">Anatomy Of A Migration</a>
203 <ul>
204
205 <li><a href="#_migrations_are_classes">Migrations are classes</a></li>
206
207 <li><a href="#_what_s_in_a_name">What's in a name</a></li>
208
209 <li><a href="#_changing_migrations">Changing migrations</a></li>
210
211 </ul>
212 </li>
213 <li>
214 <a href="#_creating_a_migration">Creating A Migration</a>
215 <ul>
216
217 <li><a href="#_creating_a_model">Creating a model</a></li>
218
219 <li><a href="#_creating_a_standalone_migration">Creating a standalone migration</a></li>
220
221 </ul>
222 </li>
223 <li>
224 <a href="#_writing_a_migration">Writing a Migration</a>
225 <ul>
226
227 <li><a href="#_creating_a_table">Creating a table</a></li>
228
229 <li><a href="#_changing_tables">Changing tables</a></li>
230
231 <li><a href="#_special_helpers">Special helpers</a></li>
232
233 <li><a href="#_writing_your_down_method">Writing your down method</a></li>
234
235 </ul>
236 </li>
237 <li>
238 <a href="#_running_migrations">Running Migrations</a>
239 <ul>
240
241 <li><a href="#_rolling_back">Rolling back</a></li>
242
243 <li><a href="#_being_specific">Being Specific</a></li>
244
245 <li><a href="#_being_talkative">Being talkative</a></li>
246
247 </ul>
248 </li>
249 <li>
250 <a href="#models">Using Models In Your Migrations</a>
251 <ul>
252
253 <li><a href="#_dealing_with_changing_models">Dealing with changing models</a></li>
254
255 </ul>
256 </li>
257 <li>
258 <a href="#_schema_dumping_and_you">Schema dumping and you</a>
259 <ul>
260
261 <li><a href="#schema">What are schema files for?</a></li>
262
263 <li><a href="#_types_of_schema_dumps">Types of schema dumps</a></li>
264
265 <li><a href="#_schema_dumps_and_source_control">Schema dumps and source control</a></li>
266
267 </ul>
268 </li>
269 <li>
270 <a href="#foreign_key">Active Record and Referential Integrity</a>
271 </li>
272 <li>
273 <a href="#_changelog">Changelog</a>
274 </li>
275 </ol>
276 </div>
277
278 <div id="content">
279 <h1>Migrations</h1>
280 <div id="preamble">
281 <div class="sectionbody">
282 <div class="para"><p>Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. 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.</p></div>
283 <div class="para"><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 CREATE TABLE any more that you worry about variations on SELECT * (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production.</p></div>
284 <div class="para"><p>You'll learn all about migrations including:</p></div>
285 <div class="ilist"><ul>
286 <li>
287 <p>
288 The generators you can use to create them
289 </p>
290 </li>
291 <li>
292 <p>
293 The methods Active Record provides to manipulate your database
294 </p>
295 </li>
296 <li>
297 <p>
298 The Rake tasks that manipulate them
299 </p>
300 </li>
301 <li>
302 <p>
303 How they relate to <tt>schema.rb</tt>
304 </p>
305 </li>
306 </ul></div>
307 </div>
308 </div>
309 <h2 id="_anatomy_of_a_migration">1. Anatomy Of A Migration</h2>
310 <div class="sectionbody">
311 <div class="para"><p>Before I dive into the details of a migration, here are a few examples of the sorts of things you can do:</p></div>
312 <div class="listingblock">
313 <div class="content"><!-- Generator: GNU source-highlight 2.9
314 by Lorenzo Bettini
315 http://www.lorenzobettini.it
316 http://www.gnu.org/software/src-highlite -->
317 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreateProducts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
318 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
319 create_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
320 t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name
321 t<span style="color: #990000">.</span>text <span style="color: #990000">:</span>description
322
323 t<span style="color: #990000">.</span>timestamps
324 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
325 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
326
327 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
328 drop_table <span style="color: #990000">:</span>products
329 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
330 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
331 </tt></pre></div></div>
332 <div class="para"><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></div>
333 <div class="para"><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></div>
334 <div class="listingblock">
335 <div class="content"><!-- Generator: GNU source-highlight 2.9
336 by Lorenzo Bettini
337 http://www.lorenzobettini.it
338 http://www.gnu.org/software/src-highlite -->
339 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AddReceiveNewsletterToUsers <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
340 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
341 change_table <span style="color: #990000">:</span>users <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
342 t<span style="color: #990000">.</span>boolean <span style="color: #990000">:</span>receive_newsletter<span style="color: #990000">,</span> <span style="color: #990000">:</span>default <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
343 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
344 User<span style="color: #990000">.</span>update_all <span style="color: #990000">[</span><span style="color: #FF0000">"receive_newsletter = ?"</span><span style="color: #990000">,</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span><span style="color: #990000">]</span>
345 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
346
347 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
348 remove_column <span style="color: #990000">:</span>users<span style="color: #990000">,</span> <span style="color: #990000">:</span>receive_newsletter
349 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
350 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
351 </tt></pre></div></div>
352 <div class="para"><p>This migration adds an <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
353 to have already opted in, so we use the User model to set the flag to <tt>true</tt> for existing users.</p></div>
354 <div class="admonitionblock">
355 <table><tr>
356 <td class="icon">
357 <img src="./images/icons/note.png" alt="Note" />
358 </td>
359 <td class="content">Some <a href="#models">caveats</a> apply to using models in your migrations.</td>
360 </tr></table>
361 </div>
362 <h3 id="_migrations_are_classes">1.1. Migrations are classes</h3>
363 <div class="para"><p>A migration is a subclass of ActiveRecord::Migration that implements two class methods: <tt>up</tt> (perform the required transformations) and <tt>down</tt> (revert them).</p></div>
364 <div class="para"><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></div>
365 <div class="ilist"><ul>
366 <li>
367 <p>
368 <tt>create_table</tt>
369 </p>
370 </li>
371 <li>
372 <p>
373 <tt>change_table</tt>
374 </p>
375 </li>
376 <li>
377 <p>
378 <tt>drop_table</tt>
379 </p>
380 </li>
381 <li>
382 <p>
383 <tt>add_column</tt>
384 </p>
385 </li>
386 <li>
387 <p>
388 <tt>remove_column</tt>
389 </p>
390 </li>
391 <li>
392 <p>
393 <tt>change_column</tt>
394 </p>
395 </li>
396 <li>
397 <p>
398 <tt>rename_column</tt>
399 </p>
400 </li>
401 <li>
402 <p>
403 <tt>add_index</tt>
404 </p>
405 </li>
406 <li>
407 <p>
408 <tt>remove_index</tt>
409 </p>
410 </li>
411 </ul></div>
412 <div class="para"><p>If you need to perform tasks specific to your database (for example create a <a href="#foreign_key">foreign key</a> constraint) then the <tt>execute</tt> function allows you to execute arbitrary SQL. A migration is just a regular Ruby class so you're not limited to these functions. For example after adding a column you could
413 write code to set the value of that column for existing records (if necessary using your models).</p></div>
414 <div class="para"><p>On databases that support transactions with statements that change the schema (such as PostgreSQL), migrations are wrapped in a transaction. If the database does not support this (for example MySQL and SQLite) 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></div>
415 <h3 id="_what_s_in_a_name">1.2. What's in a name</h3>
416 <div class="para"><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 UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The migration class' name must match (the camelcased version of) the latter part of the file name. For example <tt>20080906120000_create_products.rb</tt> should define CreateProducts and <tt>20080906120001_add_details_to_products.rb</tt> should define AddDetailsToProducts. If you do feel the need to change the file name then you MUST update the name of the class inside or Rails will complain about a missing class.</p></div>
417 <div class="para"><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 setting <tt>config.active_record.timestamped_migrations</tt> to <tt>false</tt> in <tt>environment.rb</tt>.</p></div>
418 <div class="para"><p>The combination of timestamps and recording which migrations have been run allows Rails to handle common situations that occur with multiple developers.</p></div>
419 <div class="para"><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 down methods.</p></div>
420 <div class="para"><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 the existence of then trouble will still occur.</p></div>
421 <h3 id="_changing_migrations">1.3. Changing migrations</h3>
422 <div class="para"><p>Occasionally you will make a mistake while 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></div>
423 <div class="para"><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. Just use some common sense.</p></div>
424 </div>
425 <h2 id="_creating_a_migration">2. Creating A Migration</h2>
426 <div class="sectionbody">
427 <h3 id="_creating_a_model">2.1. Creating a model</h3>
428 <div class="para"><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 those will also be created. For example, running</p></div>
429 <div class="para"><p><tt>ruby script/generate model Product name:string description:text</tt> will create a migration that looks like this</p></div>
430 <div class="listingblock">
431 <div class="content"><!-- Generator: GNU source-highlight 2.9
432 by Lorenzo Bettini
433 http://www.lorenzobettini.it
434 http://www.gnu.org/software/src-highlite -->
435 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreateProducts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
436 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
437 create_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
438 t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name
439 t<span style="color: #990000">.</span>text <span style="color: #990000">:</span>description
440
441 t<span style="color: #990000">.</span>timestamps
442 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
443 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
444
445 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
446 drop_table <span style="color: #990000">:</span>products
447 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
448 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
449 </tt></pre></div></div>
450 <div class="para"><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
451 are automatically populated by Active Record) will be added for you.</p></div>
452 <h3 id="_creating_a_standalone_migration">2.2. Creating a standalone migration</h3>
453 <div class="para"><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></div>
454 <div class="para"><p><tt>ruby script/generate migration AddPartNumberToProducts</tt></p></div>
455 <div class="para"><p>This will create an empty but appropriately named migration:</p></div>
456 <div class="listingblock">
457 <div class="content"><!-- Generator: GNU source-highlight 2.9
458 by Lorenzo Bettini
459 http://www.lorenzobettini.it
460 http://www.gnu.org/software/src-highlite -->
461 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AddPartNumberToProducts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
462 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
463 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
464
465 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
466 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
467 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
468 </tt></pre></div></div>
469 <div class="para"><p>If the migration name is of the form AddXXXToYYY or RemoveXXXFromY and is followed by a list of column names and types then a migration containing
470 the appropriate add and remove column statements will be created.</p></div>
471 <div class="para"><p><tt>ruby script/generate migration AddPartNumberToProducts part_number:string</tt></p></div>
472 <div class="para"><p>will generate</p></div>
473 <div class="listingblock">
474 <div class="content"><!-- Generator: GNU source-highlight 2.9
475 by Lorenzo Bettini
476 http://www.lorenzobettini.it
477 http://www.gnu.org/software/src-highlite -->
478 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AddPartNumberToProducts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
479 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
480 add_column <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>part_number<span style="color: #990000">,</span> <span style="color: #990000">:</span>string
481 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
482
483 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
484 remove_column <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>part_number
485 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
486 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
487 </tt></pre></div></div>
488 <div class="para"><p>Similarly,</p></div>
489 <div class="para"><p><tt>ruby script/generate migration RemovePartNumberFromProducts part_number:string</tt></p></div>
490 <div class="para"><p>generates</p></div>
491 <div class="listingblock">
492 <div class="content"><!-- Generator: GNU source-highlight 2.9
493 by Lorenzo Bettini
494 http://www.lorenzobettini.it
495 http://www.gnu.org/software/src-highlite -->
496 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> RemovePartNumberFromProducts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
497 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
498 remove_column <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>part_number
499 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
500
501 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
502 add_column <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>part_number<span style="color: #990000">,</span> <span style="color: #990000">:</span>string
503 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
504 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
505 </tt></pre></div></div>
506 <div class="para"><p>You are not limited to one magically generated column, for example</p></div>
507 <div class="para"><p><tt>ruby script/generate migration AddDetailsToProducts part_number:string price:decimal</tt></p></div>
508 <div class="para"><p>generates</p></div>
509 <div class="listingblock">
510 <div class="content"><!-- Generator: GNU source-highlight 2.9
511 by Lorenzo Bettini
512 http://www.lorenzobettini.it
513 http://www.gnu.org/software/src-highlite -->
514 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AddDetailsToProducts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
515 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
516 add_column <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>part_number<span style="color: #990000">,</span> <span style="color: #990000">:</span>string
517 add_column <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>price<span style="color: #990000">,</span> <span style="color: #990000">:</span>decimal
518 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
519
520 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
521 remove_column <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>price
522 remove_column <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>part_number
523 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
524 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
525 </tt></pre></div></div>
526 <div class="para"><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></div>
527 </div>
528 <h2 id="_writing_a_migration">3. Writing a Migration</h2>
529 <div class="sectionbody">
530 <div class="para"><p>Once you have created your migration using one of the generators it's time to get to work!</p></div>
531 <h3 id="_creating_a_table">3.1. Creating a table</h3>
532 <div class="para"><p><tt>create_table</tt> will be one of your workhorses. A typical use would be</p></div>
533 <div class="listingblock">
534 <div class="content"><!-- Generator: GNU source-highlight 2.9
535 by Lorenzo Bettini
536 http://www.lorenzobettini.it
537 http://www.gnu.org/software/src-highlite -->
538 <pre><tt>create_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
539 t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name
540 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
541 </tt></pre></div></div>
542 <div class="para"><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></div>
543 <div class="para"><p>The object yielded to the block allows you create columns on the table. There are two ways of doing this. The first looks like</p></div>
544 <div class="listingblock">
545 <div class="content"><!-- Generator: GNU source-highlight 2.9
546 by Lorenzo Bettini
547 http://www.lorenzobettini.it
548 http://www.gnu.org/software/src-highlite -->
549 <pre><tt>create_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
550 t<span style="color: #990000">.</span>column <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>string<span style="color: #990000">,</span> <span style="color: #990000">:</span>null <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
551 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
552 </tt></pre></div></div>
553 <div class="para"><p>the second form, the so called "sexy" migrations, drops the somewhat redundant column method. Instead, the <tt>string</tt>, <tt>integer</tt> etc. methods create a column of that type. Subsequent parameters are identical.</p></div>
554 <div class="listingblock">
555 <div class="content"><!-- Generator: GNU source-highlight 2.9
556 by Lorenzo Bettini
557 http://www.lorenzobettini.it
558 http://www.gnu.org/software/src-highlite -->
559 <pre><tt>create_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
560 t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>null <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
561 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
562 </tt></pre></div></div>
563 <div class="para"><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 HABTM join table) you can pass <tt>:id &#8658; false</tt>. If you need to pass database specific options you can place an sql fragment in the <tt>:options</tt> option. For example</p></div>
564 <div class="listingblock">
565 <div class="content"><!-- Generator: GNU source-highlight 2.9
566 by Lorenzo Bettini
567 http://www.lorenzobettini.it
568 http://www.gnu.org/software/src-highlite -->
569 <pre><tt>create_table <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>options <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"ENGINE=BLACKHOLE"</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
570 t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>null <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
571 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
572 </tt></pre></div></div>
573 <div class="para"><p>Will append <tt>ENGINE=BLACKHOLE</tt> to the sql used to create the table (when using MySQL the default is "ENGINE=InnoDB").</p></div>
574 <div class="para"><p>The types Active Record supports are <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>, <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>, <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>, <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>.</p></div>
575 <div class="para"><p>These will be mapped onto an appropriate underlying database type, for example with MySQL <tt>:string</tt> is mapped to <tt>VARCHAR(255)</tt>. You can create columns of
576 types not supported by Active Record when using the non sexy syntax, for example</p></div>
577 <div class="listingblock">
578 <div class="content"><!-- Generator: GNU source-highlight 2.9
579 by Lorenzo Bettini
580 http://www.lorenzobettini.it
581 http://www.gnu.org/software/src-highlite -->
582 <pre><tt>create_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
583 t<span style="color: #990000">.</span>column <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #FF0000">'polygon'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>null <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
584 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
585 </tt></pre></div></div>
586 <div class="para"><p>This may however hinder portability to other databases.</p></div>
587 <h3 id="_changing_tables">3.2. Changing tables</h3>
588 <div class="para"><p><tt>create_table</tt>'s close cousin 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></div>
589 <div class="listingblock">
590 <div class="content"><!-- Generator: GNU source-highlight 2.9
591 by Lorenzo Bettini
592 http://www.lorenzobettini.it
593 http://www.gnu.org/software/src-highlite -->
594 <pre><tt>change_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
595 t<span style="color: #990000">.</span>remove <span style="color: #990000">:</span>description<span style="color: #990000">,</span> <span style="color: #990000">:</span>name
596 t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>part_number
597 t<span style="color: #990000">.</span>index <span style="color: #990000">:</span>part_number
598 t<span style="color: #990000">.</span>rename <span style="color: #990000">:</span>upccode<span style="color: #990000">,</span> <span style="color: #990000">:</span>upc_code
599 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
600 </tt></pre></div></div>
601 <div class="para"><p>removes the <tt>description</tt> column, 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></div>
602 <div class="listingblock">
603 <div class="content"><!-- Generator: GNU source-highlight 2.9
604 by Lorenzo Bettini
605 http://www.lorenzobettini.it
606 http://www.gnu.org/software/src-highlite -->
607 <pre><tt>remove_column <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>description
608 remove_column <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>name
609 add_column <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>part_number<span style="color: #990000">,</span> <span style="color: #990000">:</span>string
610 add_index <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>part_number
611 rename_column <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>upccode<span style="color: #990000">,</span> <span style="color: #990000">:</span>upc_code
612 </tt></pre></div></div>
613 <div class="para"><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></div>
614 <h3 id="_special_helpers">3.3. Special helpers</h3>
615 <div class="para"><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></div>
616 <div class="listingblock">
617 <div class="content"><!-- Generator: GNU source-highlight 2.9
618 by Lorenzo Bettini
619 http://www.lorenzobettini.it
620 http://www.gnu.org/software/src-highlite -->
621 <pre><tt>create_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
622 t<span style="color: #990000">.</span>timestamps
623 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
624 </tt></pre></div></div>
625 <div class="para"><p>will create a new products table with those two columns whereas</p></div>
626 <div class="listingblock">
627 <div class="content"><!-- Generator: GNU source-highlight 2.9
628 by Lorenzo Bettini
629 http://www.lorenzobettini.it
630 http://www.gnu.org/software/src-highlite -->
631 <pre><tt>change_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
632 t<span style="color: #990000">.</span>timestamps
633 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
634 </tt></pre></div></div>
635 <div class="para"><p>adds those columns to an existing table.</p></div>
636 <div class="para"><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></div>
637 <div class="listingblock">
638 <div class="content"><!-- Generator: GNU source-highlight 2.9
639 by Lorenzo Bettini
640 http://www.lorenzobettini.it
641 http://www.gnu.org/software/src-highlite -->
642 <pre><tt>create_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
643 t<span style="color: #990000">.</span>references <span style="color: #990000">:</span>category
644 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
645 </tt></pre></div></div>
646 <div class="para"><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 belongs_to associations then <tt>references</tt> will add both of the columns required:</p></div>
647 <div class="listingblock">
648 <div class="content"><!-- Generator: GNU source-highlight 2.9
649 by Lorenzo Bettini
650 http://www.lorenzobettini.it
651 http://www.gnu.org/software/src-highlite -->
652 <pre><tt>create_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
653 t<span style="color: #990000">.</span>references <span style="color: #990000">:</span>attachment<span style="color: #990000">,</span> <span style="color: #990000">:</span>polymorphic <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>default <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'Photo'</span><span style="color: #FF0000">}</span>
654 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
655 </tt></pre></div></div>
656 <div class="para"><p>will add an <tt>attachment_id</tt> column and a string <tt>attachment_type</tt> column with a default value of <em>Photo</em>.</p></div>
657 <div class="admonitionblock">
658 <table><tr>
659 <td class="icon">
660 <img src="./images/icons/note.png" alt="Note" />
661 </td>
662 <td class="content">The <tt>references</tt> helper does not actually create foreign key constraints for you. You will need to use <tt>execute</tt> for that or a plugin that adds <a href="#foreign_key">foreign key support</a>.</td>
663 </tr></table>
664 </div>
665 <div class="para"><p>If the helpers provided by Active Record aren't enough you can use the <tt>execute</tt> function to execute arbitrary SQL.</p></div>
666 <div class="para"><p>For more details and examples of individual methods check the API documentation, in particular the documentation for <a href="http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html">ActiveRecord::ConnectionAdapters::SchemaStatements</a> (which provides the methods available in the <tt>up</tt> and <tt>down</tt> methods), <a href="http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html">ActiveRecord::ConnectionAdapters::TableDefinition</a> (which provides the methods available on the object yielded by <tt>create_table</tt>) and <a href="http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/Table.html">ActiveRecord::ConnectionAdapters::Table</a> (which provides the methods available on the object yielded by <tt>change_table</tt>).</p></div>
667 <h3 id="_writing_your_down_method">3.4. Writing your down method</h3>
668 <div class="para"><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 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 up you should drop it in the <tt>down</tt> method. It is wise to do things in precisely the reverse order to in the <tt>up</tt> method. For example</p></div>
669 <div class="listingblock">
670 <div class="content"><!-- Generator: GNU source-highlight 2.9
671 by Lorenzo Bettini
672 http://www.lorenzobettini.it
673 http://www.gnu.org/software/src-highlite -->
674 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ExampleMigration <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
675
676 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
677 create_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
678 t<span style="color: #990000">.</span>references <span style="color: #990000">:</span>category
679 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
680 <span style="font-style: italic"><span style="color: #9A1900">#add a foreign key</span></span>
681 execute <span style="color: #FF0000">"ALTER TABLE products ADD CONSTRAINT fk_products_categories FOREIGN KEY (category_id) REFERENCES categories(id)"</span>
682
683 add_column <span style="color: #990000">:</span>users<span style="color: #990000">,</span> <span style="color: #990000">:</span>home_page_url<span style="color: #990000">,</span> <span style="color: #990000">:</span>string
684
685 rename_column <span style="color: #990000">:</span>users<span style="color: #990000">,</span> <span style="color: #990000">:</span>email<span style="color: #990000">,</span> <span style="color: #990000">:</span>email_address
686 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
687
688 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
689 rename_column <span style="color: #990000">:</span>users<span style="color: #990000">,</span> <span style="color: #990000">:</span>email_address<span style="color: #990000">,</span> <span style="color: #990000">:</span>email
690 remove_column <span style="color: #990000">:</span>users<span style="color: #990000">,</span> <span style="color: #990000">:</span>home_page_url
691 execute <span style="color: #FF0000">"ALTER TABLE products DROP FOREIGN KEY fk_products_categories"</span>
692 drop_table <span style="color: #990000">:</span>products
693 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
694 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
695 </tt></pre></div></div>
696 <div class="para"><p>Sometimes your migration will do something which is just plain irreversible, for example it might destroy some data. In cases like those when you can't reverse the migration you can raise IrreversibleMigration from your <tt>down</tt> method. If someone tries to revert your migration an error message will be
697 displayed saying that it can't be done.</p></div>
698 </div>
699 <h2 id="_running_migrations">4. Running Migrations</h2>
700 <div class="sectionbody">
701 <div class="para"><p>Rails provides a set of rake tasks to work with migrations which boils down to running certain sets of migrations. The very first migration related rake task you 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></div>
702 <div class="para"><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
703 version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run</p></div>
704 <div class="listingblock">
705 <div class="content">
706 <pre><tt>rake db:migrate VERSION=20080906120000</tt></pre>
707 </div></div>
708 <div class="para"><p>If this 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></div>
709 <h3 id="_rolling_back">4.1. Rolling back</h3>
710 <div class="para"><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></div>
711 <div class="listingblock">
712 <div class="content">
713 <pre><tt>rake db:rollback</tt></pre>
714 </div></div>
715 <div class="para"><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></div>
716 <div class="listingblock">
717 <div class="content">
718 <pre><tt>rake db:rollback STEP=3</tt></pre>
719 </div></div>
720 <div class="para"><p>will run the <tt>down</tt> method from the last 3 migrations.</p></div>
721 <div class="para"><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></div>
722 <div class="listingblock">
723 <div class="content">
724 <pre><tt>rake db:migrate:redo STEP=3</tt></pre>
725 </div></div>
726 <div class="para"><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></div>
727 <div class="para"><p>Lastly, the <tt>db:reset</tt> task will drop the database, recreate it and load the current schema into it.</p></div>
728 <div class="admonitionblock">
729 <table><tr>
730 <td class="icon">
731 <img src="./images/icons/note.png" alt="Note" />
732 </td>
733 <td class="content">This is not the same as running all the migrations - see the section on <a href="#schema">schema.rb</a>.</td>
734 </tr></table>
735 </div>
736 <h3 id="_being_specific">4.2. Being Specific</h3>
737 <div class="para"><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></div>
738 <div class="listingblock">
739 <div class="content">
740 <pre><tt>rake db:migrate:up VERSION=20080906120000</tt></pre>
741 </div></div>
742 <div class="para"><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></div>
743 <h3 id="_being_talkative">4.3. Being talkative</h3>
744 <div class="para"><p>By default migrations tell you exactly what they're doing and how long it took.
745 A migration creating a table and adding an index might produce output like this</p></div>
746 <div class="listingblock">
747 <div class="content">
748 <pre><tt>== 20080906170109 CreateProducts: migrating ===================================
749 -- create_table(:products)
750 -&gt; 0.0021s
751 -- add_index(:products, :name)
752 -&gt; 0.0026s
753 == 20080906170109 CreateProducts: migrated (0.0059s) ==========================</tt></pre>
754 </div></div>
755 <div class="para"><p>Several methods are provided that allow you to control all this:</p></div>
756 <div class="ilist"><ul>
757 <li>
758 <p>
759 <tt>suppress_messages</tt> suppresses any output generated by its block
760 </p>
761 </li>
762 <li>
763 <p>
764 <tt>say</tt> outputs text (the second argument controls whether it is indented or not)
765 </p>
766 </li>
767 <li>
768 <p>
769 <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.
770 </p>
771 </li>
772 </ul></div>
773 <div class="para"><p>For example, this migration</p></div>
774 <div class="listingblock">
775 <div class="content"><!-- Generator: GNU source-highlight 2.9
776 by Lorenzo Bettini
777 http://www.lorenzobettini.it
778 http://www.gnu.org/software/src-highlite -->
779 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreateProducts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
780 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
781 suppress_messages <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
782 create_table <span style="color: #990000">:</span>products <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
783 t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name
784 t<span style="color: #990000">.</span>text <span style="color: #990000">:</span>description
785 t<span style="color: #990000">.</span>timestamps
786 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
787 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
788 say <span style="color: #FF0000">"Created a table"</span>
789 suppress_messages <span style="color: #FF0000">{</span>add_index <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>name<span style="color: #FF0000">}</span>
790 say <span style="color: #FF0000">"and an index!"</span><span style="color: #990000">,</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
791 say_with_time <span style="color: #FF0000">'Waiting for a while'</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
792 sleep <span style="color: #993399">10</span>
793 <span style="color: #993399">250</span>
794 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
795 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
796
797 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
798 drop_table <span style="color: #990000">:</span>products
799 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
800 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
801 </tt></pre></div></div>
802 <div class="para"><p>generates the following output</p></div>
803 <div class="listingblock">
804 <div class="content">
805 <pre><tt>== 20080906170109 CreateProducts: migrating ===================================
806 -- Created a table
807 -&gt; and an index!
808 -- Waiting for a while
809 -&gt; 10.0001s
810 -&gt; 250 rows
811 == 20080906170109 CreateProducts: migrated (10.0097s) =========================</tt></pre>
812 </div></div>
813 <div class="para"><p>If you just want Active Record to shut up then running <tt>rake db:migrate VERBOSE=false</tt> will suppress any output.</p></div>
814 </div>
815 <h2 id="models">5. Using Models In Your Migrations</h2>
816 <div class="sectionbody">
817 <div class="para"><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></div>
818 <div class="para"><p>Consider for example a migration that uses the Product model to update a row in the corresponding table. Alice later updates the Product model, adding a new column and a validation on it. Bob comes back from holiday, updates the source and runs outstanding migrations with <tt>rake db:migrate</tt>, including the one that used the Product model. When the migration runs the source is up to date and so the Product model has the validation added by Alice. The database however is still old and so does not have that column and an error ensues because that validation is on a column that does not yet exist.</p></div>
819 <div class="para"><p>Frequently I just want to update rows in the database without writing out the SQL by hand: I'm not using anything specific to the model. One pattern for this is to define a copy of the model inside the migration itself, for example:</p></div>
820 <div class="listingblock">
821 <div class="content"><!-- Generator: GNU source-highlight 2.9
822 by Lorenzo Bettini
823 http://www.lorenzobettini.it
824 http://www.gnu.org/software/src-highlite -->
825 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AddPartNumberToProducts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
826 <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Product <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
827 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
828
829 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
830 <span style="color: #990000">...</span>
831 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
832
833 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
834 <span style="color: #990000">...</span>
835 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
836 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
837 </tt></pre></div></div>
838 <div class="para"><p>The migration has its own minimal copy of the Product model and no longer cares about the Product model defined in the application.</p></div>
839 <h3 id="_dealing_with_changing_models">5.1. Dealing with changing models</h3>
840 <div class="para"><p>For performance reasons information about the columns a model has is cached. For example if you add a column to a table and then try and use the corresponding model to insert a new row it may try and use the old column information. You can force Active Record to re-read the column information with the <tt>reset_column_information</tt> method, for example</p></div>
841 <div class="listingblock">
842 <div class="content"><!-- Generator: GNU source-highlight 2.9
843 by Lorenzo Bettini
844 http://www.lorenzobettini.it
845 http://www.gnu.org/software/src-highlite -->
846 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AddPartNumberToProducts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
847 <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Product <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
848 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
849
850 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
851 add_column <span style="color: #990000">:</span>product<span style="color: #990000">,</span> <span style="color: #990000">:</span>part_number<span style="color: #990000">,</span> <span style="color: #990000">:</span>string
852 Product<span style="color: #990000">.</span>reset_column_information
853 <span style="color: #990000">...</span>
854 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
855
856 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
857 <span style="color: #990000">...</span>
858 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
859 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
860 </tt></pre></div></div>
861 </div>
862 <h2 id="_schema_dumping_and_you">6. Schema dumping and you</h2>
863 <div class="sectionbody">
864 <h3 id="schema">6.1. What are schema files for?</h3>
865 <div class="para"><p>Migrations, mighty as they may be, are not the authoritative source for your database schema. That role falls to either <tt>schema.rb</tt> or an SQL 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></div>
866 <div class="para"><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></div>
867 <div class="para"><p>For example, this is how the test database is created: the current development database is dumped (either to <tt>schema.rb</tt> or <tt>development.sql</tt>) and then loaded into the test database.</p></div>
868 <div class="para"><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 all summed up in the schema file. The <a href="http://agilewebdevelopment.com/plugins/annotate_models">annotate_models</a> plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.</p></div>
869 <h3 id="_types_of_schema_dumps">6.2. Types of schema dumps</h3>
870 <div class="para"><p>There are two ways to dump the schema. This is set in <tt>config/environment.rb</tt> by the <tt>config.active_record.schema_format</tt> setting, which may be either <tt>:sql</tt> or <tt>:ruby</tt>.</p></div>
871 <div class="para"><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></div>
872 <div class="listingblock">
873 <div class="content"><!-- Generator: GNU source-highlight 2.9
874 by Lorenzo Bettini
875 http://www.lorenzobettini.it
876 http://www.gnu.org/software/src-highlite -->
877 <pre><tt>ActiveRecord<span style="color: #990000">::</span>Schema<span style="color: #990000">.</span>define<span style="color: #990000">(:</span>version <span style="color: #990000">=&gt;</span> <span style="color: #993399">20080906171750</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
878 create_table <span style="color: #FF0000">"authors"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>force <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
879 t<span style="color: #990000">.</span>string <span style="color: #FF0000">"name"</span>
880 t<span style="color: #990000">.</span>datetime <span style="color: #FF0000">"created_at"</span>
881 t<span style="color: #990000">.</span>datetime <span style="color: #FF0000">"updated_at"</span>
882 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
883
884 create_table <span style="color: #FF0000">"products"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>force <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
885 t<span style="color: #990000">.</span>string <span style="color: #FF0000">"name"</span>
886 t<span style="color: #990000">.</span>text <span style="color: #FF0000">"description"</span>
887 t<span style="color: #990000">.</span>datetime <span style="color: #FF0000">"created_at"</span>
888 t<span style="color: #990000">.</span>datetime <span style="color: #FF0000">"updated_at"</span>
889 t<span style="color: #990000">.</span>string <span style="color: #FF0000">"part_number"</span>
890 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
891 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
892 </tt></pre></div></div>
893 <div class="para"><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></div>
894 <div class="para"><p>There is however a trade-off: <tt>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 SQL 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></div>
895 <div class="para"><p>Instead of using Active Record's schema dumper the database's structure will be dumped using a tool specific to that database (via the <tt>db:structure:dump</tt> Rake task) into <tt>db/#{RAILS_ENV}_structure.sql</tt>. For example for PostgreSQL the <tt>pg_dump</tt> utility is used and for MySQL this file will contain the output of SHOW CREATE TABLE for the various tables. Loading this schema is simply a question of executing the SQL statements contained inside.</p></div>
896 <div class="para"><p>By definition this will be a perfect copy of the database's structure but this will usually prevent loading the schema into a database other than the one used to create it.</p></div>
897 <h3 id="_schema_dumps_and_source_control">6.3. Schema dumps and source control</h3>
898 <div class="para"><p>Because they are the authoritative source for your database schema, it is strongly recommended that you check them into source control.</p></div>
899 </div>
900 <h2 id="foreign_key">7. Active Record and Referential Integrity</h2>
901 <div class="sectionbody">
902 <div class="para"><p>The Active Record way is 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></div>
903 <div class="para"><p>Validations such as <tt>validates_uniqueness_of</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></div>
904 <div class="para"><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 SQL. There are also a number of plugins such as <a href="http://agilewebdevelopment.com/plugins/search?search=redhillonrails">redhillonrails</a> which add foreign key support to Active Record (including support for dumping foreign keys in <tt>schema.rb</tt>).</p></div>
905 </div>
906 <h2 id="_changelog">8. Changelog</h2>
907 <div class="sectionbody">
908 <div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/6">Lighthouse ticket</a></p></div>
909 <div class="ilist"><ul>
910 <li>
911 <p>
912 September 14, 2008: initial version by <a href="../authors.html#fcheung">Frederick Cheung</a>
913 </p>
914 </li>
915 </ul></div>
916 </div>
917
918 </div>
919 </div>
920 </body>
921 </html>