migrations.md 32.1 KB
Newer Older
1 2
Migrations
==========
3

J
Jason Noble 已提交
4 5 6 7 8 9 10
Migrations are a convenient way for you to alter your database in a structured
and organized 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 them.
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
11 12
do is update your source and run `rake db:migrate`. Active Record will work out
which migrations should be run. Active Record will also update your `db/schema.rb` file to match the up-to-date structure of your database.
J
Jason Noble 已提交
13 14 15 16

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
17
`CREATE TABLE` any more than you worry about variations on `SELECT *` (you can
18
drop down to raw SQL for database specific features). For example, you could use
J
Jason Noble 已提交
19
SQLite3 in development, but MySQL in production.
20

21
In this guide, you'll learn all about migrations including:
22

V
Vijay Dev 已提交
23 24 25
* The generators you can use to create them
* The methods Active Record provides to manipulate your database
* The Rake tasks that manipulate them
26
* How they relate to `schema.rb`
27

28
--------------------------------------------------------------------------------
29

30 31
Anatomy of a Migration
----------------------
32

J
Jason Noble 已提交
33 34
Before we dive into the details of a migration, here are a few examples of the
sorts of things you can do:
35

36
```ruby
37
class CreateProducts < ActiveRecord::Migration
38
  def up
V
Vijay Dev 已提交
39
    create_table :products do |t|
40 41 42 43 44 45 46
      t.string :name
      t.text :description

      t.timestamps
    end
  end

47
  def down
48 49 50
    drop_table :products
  end
end
51
```
52

53 54
This migration adds a table called `products` with a string column called `name`
and a text column called `description`. A primary key column called `id` will
V
Vijay Dev 已提交
55
also be added, however since this is the default we do not need to explicitly specify it.
56
The timestamp columns `created_at` and `updated_at` which Active Record
J
Jason Noble 已提交
57 58
populates automatically will also be added. Reversing this migration is as
simple as dropping the table.
59

J
Jason Noble 已提交
60 61
Migrations are not limited to changing the schema. You can also use them to fix
bad data in the database or populate new fields:
62

63
```ruby
64
class AddReceiveNewsletterToUsers < ActiveRecord::Migration
65
  def up
V
Vijay Dev 已提交
66
    change_table :users do |t|
67 68
      t.boolean :receive_newsletter, :default => false
    end
V
Vijay Dev 已提交
69
    User.update_all :receive_newsletter => true
70 71
  end

72
  def down
73 74 75
    remove_column :users, :receive_newsletter
  end
end
76
```
77

78
NOTE: Some [caveats](#using-models-in-your-migrations) apply to using models in
J
Jason Noble 已提交
79
your migrations.
V
Vijay Dev 已提交
80

81 82 83
This migration adds a `receive_newsletter` column to the `users` table. We want
it to default to `false` for new users, but existing users are considered to
have already opted in, so we use the User model to set the flag to `true` for
J
Jason Noble 已提交
84
existing users.
85

86
### Using the change method
87

88
Rails 3.1 makes migrations smarter by providing a new `change` method.
J
Jason Noble 已提交
89 90
This method is preferred for writing constructive migrations (adding columns or
tables). The migration knows how to migrate your database and reverse it when
91
the migration is rolled back without the need to write a separate `down` method.
92

93
```ruby
94 95
class CreateProducts < ActiveRecord::Migration
  def change
V
Vijay Dev 已提交
96
    create_table :products do |t|
97 98 99 100 101 102 103
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end
104
```
105

106
### Migrations are Classes
107

108
A migration is a subclass of `ActiveRecord::Migration` that implements
109
two methods: `up` (perform the required transformations) and `down` (revert
J
Jason Noble 已提交
110
them).
111

J
Jason Noble 已提交
112 113
Active Record provides methods that perform common data definition tasks in a
database independent way (you'll read about them in detail later):
114

115 116 117 118 119 120 121 122 123 124 125 126
* `add_column`
* `add_reference`
* `add_index`
* `change_column`
* `change_table`
* `create_table`
* `create_join_table`
* `drop_table`
* `remove_column`
* `remove_index`
* `rename_column`
* `remove_reference`
127

128
If you need to perform tasks specific to your database (e.g., create a
129
[foreign key](#active-record-and-referential-integrity) constraint) then the
130
`execute` method allows you to execute arbitrary SQL. A migration is just a
131
regular Ruby class so you're not limited to these functions. For example, after
J
Jason Noble 已提交
132 133
adding a column you could write code to set the value of that column for
existing records (if necessary using your models).
134

J
Jason Noble 已提交
135 136 137
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
138
the parts of it that succeeded will not be rolled back. You will have to rollback
J
Jason Noble 已提交
139
the changes that were made by hand.
140

141
### What's in a Name
142

143
Migrations are stored as files in the `db/migrate` directory, one for each
V
Vijay Dev 已提交
144
migration class. The name of the file is of the form
145
`YYYYMMDDHHMMSS_create_products.rb`, that is to say a UTC timestamp
V
Vijay Dev 已提交
146 147
identifying the migration followed by an underscore followed by the name
of the migration. The name of the migration class (CamelCased version)
J
Jason Noble 已提交
148
should match the latter part of the file name. For example
149 150 151
`20080906120000_create_products.rb` should define class `CreateProducts` and
`20080906120001_add_details_to_products.rb` should define
`AddDetailsToProducts`. If you do feel the need to change the file name then you
J
Jason Noble 已提交
152 153 154 155 156 157 158
<em>have to</em> update the name of the class inside or Rails will complain
about a missing class.

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
V
Vijay Dev 已提交
159
Rails 2.1+ this is largely avoided by using the creation time of the migration
J
Jason Noble 已提交
160
to identify them. You can revert to the old numbering scheme by adding the
161
following line to `config/application.rb`.
162

163
```ruby
164
config.active_record.timestamped_migrations = false
165
```
166

J
Jason Noble 已提交
167 168
The combination of timestamps and recording which migrations have been run
allows Rails to handle common situations that occur with multiple developers.
169

170 171 172 173
For example, Alice adds migrations `20080906120000` and `20080906123000` and Bob
adds `20080906124500` and runs it. Alice finishes her changes and checks in her
migrations and Bob pulls down the latest changes. When Bob runs `rake db:migrate`,
Rails knows that it has not run Alice's two migrations so it executes the `up` method for each migration.
174

J
Jason Noble 已提交
175 176 177
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.
178

179
### Changing Migrations
180

J
Jason Noble 已提交
181 182 183
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
184 185
nothing when you run `rake db:migrate`. You must rollback the migration (for
example with `rake db:rollback`), edit your migration and then run `rake db:migrate` to run the corrected version.
J
Jason Noble 已提交
186

187
In general, editing existing migrations is not a good idea. You will be creating
J
Jason Noble 已提交
188 189 190 191 192 193
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.
194

195
### Supported Types
D
Daniel Dyba 已提交
196

197 198
Active Record supports the following database column types:

199 200 201 202 203 204 205 206 207 208 209 210
* `:binary`
* `:boolean`
* `:date`
* `:datetime`
* `:decimal`
* `:float`
* `:integer`
* `:primary_key`
* `:string`
* `:text`
* `:time`
* `:timestamp`
J
Jason Noble 已提交
211 212

These will be mapped onto an appropriate underlying database type. For example,
213
with MySQL the type `:string` is mapped to `VARCHAR(255)`. You can create
214
columns of types not supported by Active Record when using the non-sexy syntax such as
D
Daniel Dyba 已提交
215

216
```ruby
D
Daniel Dyba 已提交
217 218 219
create_table :products do |t|
  t.column :name, 'polygon', :null => false
end
220
```
D
Daniel Dyba 已提交
221 222 223

This may however hinder portability to other databases.

224 225
Creating a Migration
--------------------
226

227
### Creating a Model
228

J
Jason Noble 已提交
229 230 231 232
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
233

P
Prem Sichanugrist 已提交
234
```bash
235
$ rails generate model Product name:string description:text
236
```
P
Pratik Naik 已提交
237 238

will create a migration that looks like this
239

240
```ruby
241
class CreateProducts < ActiveRecord::Migration
242
  def change
243 244 245 246 247 248 249 250
    create_table :products do |t|
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end
251
```
252

V
Vijay Dev 已提交
253
You can append as many column name/type pairs as you want. By default, the
254 255
generated migration will include `t.timestamps` (which creates the
`updated_at` and `created_at` columns that are automatically populated
256
by Active Record).
257

258
### Creating a Standalone Migration
259

260
If you are creating migrations for other purposes (e.g., to add a column
J
Jason Noble 已提交
261
to an existing table) then you can also use the migration generator:
262

P
Prem Sichanugrist 已提交
263
```bash
264
$ rails generate migration AddPartNumberToProducts
265
```
266 267 268

This will create an empty but appropriately named migration:

269
```ruby
270
class AddPartNumberToProducts < ActiveRecord::Migration
271
  def change
272 273
  end
end
274
```
275

J
Jason Noble 已提交
276 277
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
278
appropriate `add_column` and `remove_column` statements will be created.
279

P
Prem Sichanugrist 已提交
280
```bash
281
$ rails generate migration AddPartNumberToProducts part_number:string
282
```
283 284 285

will generate

286
```ruby
287
class AddPartNumberToProducts < ActiveRecord::Migration
288
  def change
289 290 291
    add_column :products, :part_number, :string
  end
end
292
```
293 294 295

Similarly,

P
Prem Sichanugrist 已提交
296
```bash
297
$ rails generate migration RemovePartNumberFromProducts part_number:string
298
```
299 300 301

generates

302
```ruby
303
class RemovePartNumberFromProducts < ActiveRecord::Migration
304
  def up
305 306 307
    remove_column :products, :part_number
  end

308
  def down
309 310 311
    add_column :products, :part_number, :string
  end
end
312
```
313

314
You are not limited to one magically generated column. For example
315

P
Prem Sichanugrist 已提交
316
```bash
317
$ rails generate migration AddDetailsToProducts part_number:string price:decimal
318
```
319 320 321

generates

322
```ruby
323
class AddDetailsToProducts < ActiveRecord::Migration
324
  def change
325 326 327 328
    add_column :products, :part_number, :string
    add_column :products, :price, :decimal
  end
end
329
```
330

J
Jason Noble 已提交
331
As always, what has been generated for you is just a starting point. You can add
V
Vijay Dev 已提交
332 333
or remove from it as you see fit by editing the
db/migrate/YYYYMMDDHHMMSS_add_details_to_products.rb file.
334

J
Jason Noble 已提交
335
NOTE: The generated migration file for destructive migrations will still be
336
old-style using the `up` and `down` methods. This is because Rails needs to know
J
Jason Noble 已提交
337
the original data types defined when you made the original changes.
V
Vijay Dev 已提交
338

339
Also, the generator accepts column type as `references`(also available as `belongs_to`). For instance
A
Aleksey Magusev 已提交
340

P
Prem Sichanugrist 已提交
341
```bash
A
Aleksey Magusev 已提交
342
$ rails generate migration AddUserRefToProducts user:references
343
```
A
Aleksey Magusev 已提交
344 345 346

generates

347
```ruby
A
Aleksey Magusev 已提交
348 349 350 351 352
class AddUserRefToProducts < ActiveRecord::Migration
  def change
    add_reference :products, :user, :index => true
  end
end
353
```
A
Aleksey Magusev 已提交
354 355 356

This migration will create a user_id column and appropriate index.

357
### Supported Type Modifiers
A
Aleksey Magusev 已提交
358 359 360 361

You can also specify some options just after the field type between curly braces. You can use the
following modifiers:

362 363 364 365
* `limit`        Sets the maximum size of the `string/text/binary/integer` fields
* `precision`    Defines the precision for the `decimal` fields
* `scale`        Defines the scale for the `decimal` fields
* `polymorphic`  Adds a `type` column for `belongs_to` associations
A
Aleksey Magusev 已提交
366

367
For instance, running
A
Aleksey Magusev 已提交
368

P
Prem Sichanugrist 已提交
369
```bash
A
Aleksey Magusev 已提交
370
$ rails generate migration AddDetailsToProducts price:decimal{5,2} supplier:references{polymorphic}
371
```
A
Aleksey Magusev 已提交
372 373 374

will produce a migration that looks like this

375
```ruby
A
Aleksey Magusev 已提交
376 377 378 379 380 381
class AddDetailsToProducts < ActiveRecord::Migration
  def change
		add_column :products, :price, :precision => 5, :scale => 2
    add_reference :products, :user, :polymorphic => true, :index => true
  end
end
382
```
A
Aleksey Magusev 已提交
383

384 385
Writing a Migration
-------------------
386

J
Jason Noble 已提交
387 388
Once you have created your migration using one of the generators it's time to
get to work!
389

390
### Creating a Table
391

392
Migration method `create_table` will be one of your workhorses. A typical use
J
Jason Noble 已提交
393
would be
394

395
```ruby
396 397 398
create_table :products do |t|
  t.string :name
end
399
```
400

401 402
which creates a `products` table with a column called `name` (and as discussed
below, an implicit `id` column).
403

J
Jason Noble 已提交
404 405
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
406

407
```ruby
408 409 410
create_table :products do |t|
  t.column :name, :string, :null => false
end
411
```
412

J
Jason Noble 已提交
413
The second form, the so called "sexy" migration, drops the somewhat redundant
414
`column` method. Instead, the `string`, `integer`, etc. methods create a column
J
Jason Noble 已提交
415
of that type. Subsequent parameters are the same.
416

417
```ruby
418 419 420
create_table :products do |t|
  t.string :name, :null => false
end
421
```
422

423 424
By default, `create_table` will create a primary key called `id`. You can change
the name of the primary key with the `:primary_key` option (don't forget to
J
Jason Noble 已提交
425
update the corresponding model) or, if you don't want a primary key at all (for
426
example for a HABTM join table), you can pass the option `:id => false`. If you
V
Vijay Dev 已提交
427
need to pass database specific options you can place an SQL fragment in the
428
`:options` option. For example,
429

430
```ruby
431 432 433
create_table :products, :options => "ENGINE=BLACKHOLE" do |t|
  t.string :name, :null => false
end
434
```
435

436 437
will append `ENGINE=BLACKHOLE` to the SQL statement used to create the table
(when using MySQL, the default is `ENGINE=InnoDB`).
P
Pratik Naik 已提交
438

439
### Creating a Join Table
440

441
Migration method `create_join_table` creates a HABTM join table. A typical use
442 443
would be

444
```ruby
445
create_join_table :products, :categories
446
```
447

448 449
which creates a `categories_products` table with two columns called `category_id` and `product_id`.
These columns have the option `:null` set to `false` by default.
450

451
You can pass the option `:table_name` with you want to customize the table name. For example,
452

453
```ruby
454
create_join_table :products, :categories, :table_name => :categorization
455
```
456

457
will create a `categorization` table.
458

459 460
By default, `create_join_table` will create two columns with no options, but you can specify these
options using the `:column_options` option. For example,
461

462
```ruby
463
create_join_table :products, :categories, :column_options => {:null => true}
464
```
465

466
will create the `product_id` and `category_id` with the `:null` option as `true`.
467

468
### Changing Tables
469

470 471
A close cousin of `create_table` is `change_table`, used for changing existing
tables. It is used in a similar fashion to `create_table` but the object yielded
J
Jason Noble 已提交
472
to the block knows more tricks. For example
473

474
```ruby
475 476 477 478 479 480
change_table :products do |t|
  t.remove :description, :name
  t.string :part_number
  t.index :part_number
  t.rename :upccode, :upc_code
end
481
```
482

483 484
removes the `description` and `name` columns, creates a `part_number` string
column and adds an index on it. Finally it renames the `upccode` column.
485

486
### Special Helpers
487

J
Jason Noble 已提交
488
Active Record provides some shortcuts for common functionality. It is for
489
example very common to add both the `created_at` and `updated_at` columns and so
J
Jason Noble 已提交
490
there is a method that does exactly that:
491

492
```ruby
493 494 495
create_table :products do |t|
  t.timestamps
end
496
```
497

498
will create a new products table with those two columns (plus the `id` column)
J
Jason Noble 已提交
499 500
whereas

501
```ruby
502 503 504
change_table :products do |t|
  t.timestamps
end
505
```
506 507
adds those columns to an existing table.

508
Another helper is called `references` (also available as `belongs_to`). In its
V
Vijay Dev 已提交
509
simplest form it just adds some readability.
510

511
```ruby
512 513 514
create_table :products do |t|
  t.references :category
end
515
```
516

517 518 519
will create a `category_id` column of the appropriate type. Note that you pass
the model name, not the column name. Active Record adds the `_id` for you. If
you have polymorphic `belongs_to` associations then `references` will add both
J
Jason Noble 已提交
520
of the columns required:
521

522
```ruby
523 524 525
create_table :products do |t|
  t.references :attachment, :polymorphic => {:default => 'Photo'}
end
526
```
527

528 529 530
will add an `attachment_id` column and a string `attachment_type` column with
a default value of 'Photo'. `references` also allows you to define an
index directly, instead of using `add_index` after the `create_table` call:
531

532
```ruby
533 534 535
create_table :products do |t|
  t.references :category, :index => true
end
536
```
537 538

will create an index identical to calling `add_index :products, :category_id`.
539

540 541
NOTE: The `references` helper does not actually create foreign key constraints
for you. You will need to use `execute` or a plugin that adds "foreign key
J
Jason Noble 已提交
542
support":#active-record-and-referential-integrity.
543

544
If the helpers provided by Active Record aren't enough you can use the `execute`
J
Jason Noble 已提交
545 546
method to execute arbitrary SQL.

547 548
For more details and examples of individual methods, check the API documentation. 
In particular the documentation for
549
[`ActiveRecord::ConnectionAdapters::SchemaStatements`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html)
550
(which provides the methods available in the `up` and `down` methods),
551
[`ActiveRecord::ConnectionAdapters::TableDefinition`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html)
552
(which provides the methods available on the object yielded by `create_table`)
J
Jason Noble 已提交
553
and
554
[`ActiveRecord::ConnectionAdapters::Table`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html)
555
(which provides the methods available on the object yielded by `change_table`).
556

557
### Using the `change` Method
558

559
The `change` method removes the need to write both `up` and `down` methods in
F
Fernando Briano 已提交
560
those cases that Rails knows how to revert the changes automatically. Currently,
561
the `change` method supports only these migration definitions:
562

563 564 565 566 567 568 569 570
* `add_column`
* `add_index`
* `add_timestamps`
* `create_table`
* `remove_timestamps`
* `rename_column`
* `rename_index`
* `rename_table`
571

V
Vijay Dev 已提交
572
If you're going to need to use any other methods, you'll have to write the
573
`up` and `down` methods instead of using the `change` method.
574

575
### Using the `up`/`down` Methods
576

577 578 579 580 581
The `down` method of your migration should revert the transformations done by
the `up` method. In other words, the database schema should be unchanged if you
do an `up` followed by a `down`. For example, if you create a table in the `up`
method, you should drop it in the `down` method. It is wise to reverse the
transformations in precisely the reverse order they were made in the `up`
J
Jason Noble 已提交
582
method. For example,
583

584
```ruby
585
class ExampleMigration < ActiveRecord::Migration
586
  def up
587 588 589 590
    create_table :products do |t|
      t.references :category
    end
    #add a foreign key
P
Pratik Naik 已提交
591 592 593 594 595 596
    execute <<-SQL
      ALTER TABLE products
        ADD CONSTRAINT fk_products_categories
        FOREIGN KEY (category_id)
        REFERENCES categories(id)
    SQL
597 598 599 600
    add_column :users, :home_page_url, :string
    rename_column :users, :email, :email_address
  end

601
  def down
602 603
    rename_column :users, :email_address, :email
    remove_column :users, :home_page_url
J
Jason Noble 已提交
604 605 606 607
    execute <<-SQL
      ALTER TABLE products
        DROP FOREIGN KEY fk_products_categories
    SQL
608 609 610
    drop_table :products
  end
end
611
```
612

J
Jason Noble 已提交
613 614
Sometimes your migration will do something which is just plain irreversible; for
example, it might destroy some data. In such cases, you can raise
615
`ActiveRecord::IrreversibleMigration` from your `down` method. If someone tries
J
Jason Noble 已提交
616 617
to revert your migration, an error message will be displayed saying that it
can't be done.
618

619 620
Running Migrations
------------------
621

J
Jason Noble 已提交
622
Rails provides a set of rake tasks to work with migrations which boil down to
V
Vijay Dev 已提交
623
running certain sets of migrations.
624

V
Vijay Dev 已提交
625
The very first migration related rake task you will use will probably be
626
`rake db:migrate`. In its most basic form it just runs the `up` or `change`
627 628 629
method for all the migrations that have not yet been run. If there are
no such migrations, it exits. It will run these migrations in order based
on the date of the migration.
630

631
Note that running the `db:migrate` also invokes the `db:schema:dump` task, which
J
Jason Noble 已提交
632
will update your db/schema.rb file to match the structure of your database.
633

J
Jason Noble 已提交
634
If you specify a target version, Active Record will run the required migrations
J
Jason Noble 已提交
635
(up, down or change) until it has reached the specified version. The version
V
Vijay Dev 已提交
636
is the numerical prefix on the migration's filename. For example, to migrate
637
to version 20080906120000 run
638

P
Prem Sichanugrist 已提交
639
```bash
640
$ rake db:migrate VERSION=20080906120000
641
```
642

J
Jason Noble 已提交
643
If version 20080906120000 is greater than the current version (i.e., it is
644
migrating upwards), this will run the `up` method on all migrations up to and
V
Vijay Dev 已提交
645
including 20080906120000, and will not execute any later migrations. If
646
migrating downwards, this will run the `down` method on all the migrations
647
down to, but not including, 20080906120000.
648

649
### Rolling Back
650

651
A common task is to rollback the last migration. For example, if you made a
J
Jason Noble 已提交
652 653
mistake in it and wish to correct it. Rather than tracking down the version
number associated with the previous migration you can run
654

P
Prem Sichanugrist 已提交
655
```bash
656
$ rake db:rollback
657
```
658

659 660
This will run the `down` method from the latest migration. If you need to undo
several migrations you can provide a `STEP` parameter:
661

P
Prem Sichanugrist 已提交
662
```bash
663
$ rake db:rollback STEP=3
664
```
665

666
will run the `down` method from the last 3 migrations.
667

668 669
The `db:migrate:redo` task is a shortcut for doing a rollback and then migrating
back up again. As with the `db:rollback` task, you can use the `STEP` parameter
J
Jason Noble 已提交
670
if you need to go more than one version back, for example
671

P
Prem Sichanugrist 已提交
672
```bash
673
$ rake db:migrate:redo STEP=3
674
```
675

676
Neither of these Rake tasks do anything you could not do with `db:migrate`. They
J
Jason Noble 已提交
677 678
are simply more convenient, since you do not need to explicitly specify the
version to migrate to.
679

680
### Resetting the Database
681

682
The `rake db:reset` task will drop the database, recreate it and load the
J
Jason Noble 已提交
683
current schema into it.
684

J
Jason Noble 已提交
685
NOTE: This is not the same as running all the migrations - see the section on
686
[schema.rb](#schema-dumping-and-you).
687

688
### Running Specific Migrations
689

690 691 692
If you need to run a specific migration up or down, the `db:migrate:up` and
`db:migrate:down` tasks will do that. Just specify the appropriate version and
the corresponding migration will have its `up` or `down` method invoked, for
J
Jason Noble 已提交
693
example,
694

P
Prem Sichanugrist 已提交
695
```bash
696
$ rake db:migrate:up VERSION=20080906120000
697
```
698

699
will run the `up` method from the 20080906120000 migration. This task will first
V
Vijay Dev 已提交
700 701
check whether the migration is already performed and will do nothing if Active Record believes
that it has already been run.
702

703
### Changing the Output of Running Migrations
704

J
Jason Noble 已提交
705 706
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
707

P
Prem Sichanugrist 已提交
708
```bash
J
Jason Noble 已提交
709
==  CreateProducts: migrating =================================================
710
-- create_table(:products)
J
Jason Noble 已提交
711 712
   -> 0.0028s
==  CreateProducts: migrated (0.0028s) ========================================
713
```
714

715 716 717
Several methods are provided in migrations that allow you to control all this:

|_.Method             |_.Purpose|
V
Vijay Dev 已提交
718
|suppress_messages    |Takes a block as an argument and suppresses any output
719 720 721 722 723
                       generated by the block.|
|say                  |Takes a message argument and outputs it as is. A second
                       boolean argument can be passed to specify whether to
                       indent or not.|
|say_with_time        |Outputs text along with how long it took to run its
V
Vijay Dev 已提交
724
                       block. If the block returns an integer it assumes it
725
                       is the number of rows affected.|
726 727 728

For example, this migration

729
```ruby
730
class CreateProducts < ActiveRecord::Migration
731
  def change
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
    suppress_messages do
      create_table :products do |t|
        t.string :name
        t.text :description
        t.timestamps
      end
    end
    say "Created a table"
    suppress_messages {add_index :products, :name}
    say "and an index!", true
    say_with_time 'Waiting for a while' do
      sleep 10
      250
    end
  end
end
748
```
749 750 751

generates the following output

P
Prem Sichanugrist 已提交
752
```bash
J
Jason Noble 已提交
753 754
==  CreateProducts: migrating =================================================
-- Created a table
755
   -> and an index!
J
Jason Noble 已提交
756 757
-- Waiting for a while
   -> 10.0013s
758
   -> 250 rows
J
Jason Noble 已提交
759
==  CreateProducts: migrated (10.0054s) =======================================
760
```
761

762 763
If you want Active Record to not output anything, then running `rake db:migrate
VERBOSE=false` will suppress all output.
764

765 766
Using Models in Your Migrations
-------------------------------
767

J
Jason Noble 已提交
768 769 770
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.
771

J
Jason Noble 已提交
772 773 774
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.
775

J
Jason Noble 已提交
776
Consider this example, where Alice and Bob are working on the same code base
777
which contains a `Product` model:
778

779 780
Bob goes on vacation.

781 782
Alice creates a migration for the `products` table which adds a new column and
initializes it.  She also adds a validation to the `Product` model for the new
J
Jason Noble 已提交
783
column.
784

785
```ruby
786 787 788 789
# db/migrate/20100513121110_add_flag_to_product.rb

class AddFlagToProduct < ActiveRecord::Migration
  def change
J
Jason Noble 已提交
790
    add_column :products, :flag, :boolean
791
    Product.update_all :flag => false
792
  end
793
end
794
```
795

796
```ruby
797 798 799
# app/model/product.rb

class Product < ActiveRecord::Base
V
Vijay Dev 已提交
800
  validates :flag, :presence => true
801
end
802
```
803

J
Jason Noble 已提交
804
Alice adds a second migration which adds and initializes another column to the
805
`products` table and also adds a validation to the `Product` model for the new
J
Jason Noble 已提交
806
column.
807

808
```ruby
809 810 811
# db/migrate/20100515121110_add_fuzz_to_product.rb

class AddFuzzToProduct < ActiveRecord::Migration
812
  def change
813
    add_column :products, :fuzz, :string
814
    Product.update_all :fuzz => 'fuzzy'
815 816
  end
end
817
```
818

819
```ruby
820
# app/model/product.rb
821

822
class Product < ActiveRecord::Base
V
Vijay Dev 已提交
823
  validates :flag, :fuzz, :presence => true
824
end
825
```
826

827 828 829 830
Both migrations work for Alice.

Bob comes back from vacation and:

L
luke 已提交
831
# Updates the source - which contains both migrations and the latest version of
J
Jason Noble 已提交
832
the Product model.
833 834
# Runs outstanding migrations with `rake db:migrate`, which
includes the one that updates the `Product` model.
835

J
Jason Noble 已提交
836 837 838
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 _first_
migration runs:
839

840
```
841 842 843 844
rake aborted!
An error has occurred, this and all later migrations canceled:

undefined method `fuzz' for #<Product:0x000001049b14a0>
845
```
846

847
A fix for this is to create a local model within the migration. This keeps Rails
J
Jason Noble 已提交
848
from running the validations, so that the migrations run to completion.
849

J
Jason Noble 已提交
850
When using a faux model, it's a good idea to call
851 852
`Product.reset_column_information` to refresh the `ActiveRecord` cache for the
`Product` model prior to updating data in the database.
853 854 855

If Alice had done this instead, there would have been no problem:

856
```ruby
857 858
# db/migrate/20100513121110_add_flag_to_product.rb

V
Vijay Dev 已提交
859
class AddFlagToProduct < ActiveRecord::Migration
860 861
  class Product < ActiveRecord::Base
  end
V
Vijay Dev 已提交
862

863
  def change
864
    add_column :products, :flag, :boolean
V
Vijay Dev 已提交
865
    Product.reset_column_information
866
    Product.update_all :flag => false
867 868
  end
end
869
```
870

871
```ruby
872 873 874 875 876
# db/migrate/20100515121110_add_fuzz_to_product.rb

class AddFuzzToProduct < ActiveRecord::Migration
  class Product < ActiveRecord::Base
  end
V
Vijay Dev 已提交
877

878
  def change
879
    add_column :products, :fuzz, :string
880
    Product.reset_column_information
881
    Product.update_all :fuzz => 'fuzzy'
882 883
  end
end
884
```
885

886 887
Schema Dumping and You
----------------------
888

889
### What are Schema Files for?
890

J
Jason Noble 已提交
891
Migrations, mighty as they may be, are not the authoritative source for your
892
database schema. That role falls to either `db/schema.rb` or an SQL file which
J
Jason Noble 已提交
893 894
Active Record generates by examining the database. They are not designed to be
edited, they just represent the current state of the database.
895

J
Jason Noble 已提交
896 897 898
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.
899

J
Jason Noble 已提交
900
For example, this is how the test database is created: the current development
901
database is dumped (either to `db/schema.rb` or `db/structure.sql`) and then
J
Jason Noble 已提交
902
loaded into the test database.
903

J
Jason Noble 已提交
904 905
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
V
Vijay Dev 已提交
906 907
frequently spread across several migrations, but the information is nicely
summed up in the schema file. The
908
[annotate_models](https://github.com/ctran/annotate_models) gem automatically
V
Vijay Dev 已提交
909
adds and updates comments at the top of each model summarizing the schema if
J
Jason Noble 已提交
910
you desire that functionality.
911

912
### Types of Schema Dumps
913

914 915 916
There are two ways to dump the schema. This is set in `config/application.rb` by
the `config.active_record.schema_format` setting, which may be either `:sql` or
`:ruby`.
917

918
If `:ruby` is selected then the schema is stored in `db/schema.rb`. If you look
J
Jason Noble 已提交
919
at this file you'll find that it looks an awful lot like one very big migration:
920

921
```ruby
922 923
ActiveRecord::Schema.define(version: 20080906171750) do
  create_table "authors", force: true do |t|
924 925 926 927 928
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

929
  create_table "products", force: true do |t|
930
    t.string   "name"
J
Jason Noble 已提交
931
    t.text "description"
932 933
    t.datetime "created_at"
    t.datetime "updated_at"
J
Jason Noble 已提交
934
    t.string "part_number"
935 936
  end
end
937
```
938

J
Jason Noble 已提交
939
In many ways this is exactly what it is. This file is created by inspecting the
940
database and expressing its structure using `create_table`, `add_index`, and so
J
Jason Noble 已提交
941 942 943 944
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.

945
There is however a trade-off: `db/schema.rb` cannot express database specific
J
Jason Noble 已提交
946 947 948
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
949
this, then you should set the schema format to `:sql`.
J
Jason Noble 已提交
950 951

Instead of using Active Record's schema dumper, the database's structure will be
952 953 954 955
dumped using a tool specific to the database (via the `db:structure:dump` Rake task)
into `db/structure.sql`. For example, for the PostgreSQL RDBMS, the
`pg_dump` utility is used. For MySQL, this file will contain the output of `SHOW
CREATE TABLE` for the various tables. Loading these schemas is simply a question
J
Jason Noble 已提交
956
of executing the SQL statements they contain. By definition, this will create a
957
perfect copy of the database's structure. Using the `:sql` schema format will,
J
Jason Noble 已提交
958 959
however, prevent loading the schema into a RDBMS other than the one used to
create it.
960

961
### Schema Dumps and Source Control
962

J
Jason Noble 已提交
963 964
Because schema dumps are the authoritative source for your database schema, it
is strongly recommended that you check them into source control.
965

966 967
Active Record and Referential Integrity
---------------------------------------
968

J
Jason Noble 已提交
969 970 971 972 973
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.

974 975
Validations such as `validates :foreign_key, :uniqueness => true` are one way in
which models can enforce data integrity. The `:dependent` option on associations
J
Jason Noble 已提交
976 977 978
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
979
constraints in the database.
J
Jason Noble 已提交
980 981

Although Active Record does not provide any tools for working directly with such
982
features, the `execute` method can be used to execute arbitrary SQL. You could
983
also use some plugin like [foreigner](https://github.com/matthuhiggins/foreigner)
J
Jason Noble 已提交
984
which add foreign key support to Active Record (including support for dumping
985
foreign keys in `db/schema.rb`).