migrations.md 34.5 KB
Newer Older
1 2
Active Record Migrations
========================
3

4 5 6 7 8
Migrations are a feature of Active Record that allows you to evolve your
database schema over time. Rather than write schema modifications in pure SQL,
migrations allow you to use an easy Ruby DSL to describe changes to your
tables.

9
After reading this guide, you will know:
10

11 12 13 14
* The generators you can use to create them.
* The methods Active Record provides to manipulate your database.
* The Rake tasks that manipulate migrations and your schema.
* How migrations relate to `schema.rb`.
15 16 17

--------------------------------------------------------------------------------

S
Steve Klabnik 已提交
18 19
Migration Overview
------------------
20

S
Steve Klabnik 已提交
21 22 23
Migrations are a convenient way to alter your database schema over time in a
consistent and easy way. They use a Ruby DSL so that you don't have to write
SQL by hand, allowing your schema and changes to be database independent.
J
Jason Noble 已提交
24

S
Steve Klabnik 已提交
25 26 27 28 29
You can think of each migration as being a new 'version' of the database. A
schema starts off with nothing in it, and each migration modifies it to add or
remove tables, columns, or entries. Active Record knows how to update your
schema along this timeline, bringing it from whatever point it is in the
history to the latest version. Active Record will also update your
30
`db/schema.rb` file to match the up-to-date structure of your database.
J
Jason Noble 已提交
31

S
Steve Klabnik 已提交
32
Here's an example of a migration:
33

34
```ruby
35
class CreateProducts < ActiveRecord::Migration
S
Steve Klabnik 已提交
36
  def change
V
Vijay Dev 已提交
37
    create_table :products do |t|
38 39 40 41 42 43 44
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end
45
```
46

S
Steve Klabnik 已提交
47 48 49 50 51 52 53 54 55 56 57 58
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 also be added implicitly, as it's the default primary key for all Active
Record models. The `timestamps` macro adds two columns, `created_at` and
`updated_at`. These special columns are automatically managed by Active Record
if they exist.

Note that we define the change that we want to happen moving forward in time.
Before this migration is run, there will be no table. After, the table will
exist. Active Record knows how to reverse this migration as well: if we roll
this migration back, it will remove the table.

59
On databases that support transactions with statements that change the schema,
S
Steve Klabnik 已提交
60 61 62
migrations are wrapped in a transaction. If the database does not support this
then when a migration fails the parts of it that succeeded will not be rolled
back. You will have to rollback the changes that were made by hand.
63

64 65 66 67
NOTE: There are certain queries that can't run inside a transaction. If your
adapter supports DDL transactions you can use `disable_ddl_transaction!` to
disable them for a single migration.

S
Steve Klabnik 已提交
68
If you wish for a migration to do something that Active Record doesn't know how
69
to reverse, you can use `reversible`:
70

71
```ruby
72 73 74 75 76 77 78 79 80 81 82 83 84 85
class ChangeProductsPrice < ActiveRecord::Migration
  def change
    reversible do |dir|
      change_table :products do |t|
        dir.up   { t.change :price, :string }
        dir.down { t.change :price, :integer }
      end
    end
  end
end
```

Alternatively, you can use `up` and `down` instead of `change`:

86
```ruby
S
Steve Klabnik 已提交
87
class ChangeProductsPrice < ActiveRecord::Migration
88
  def up
S
Steve Klabnik 已提交
89
    change_table :products do |t|
90
      t.change :price, :string
91 92
    end
  end
93

94
  def down
S
Steve Klabnik 已提交
95
    change_table :products do |t|
96
      t.change :price, :integer
97 98 99
    end
  end
end
100
```
101

S
Steve Klabnik 已提交
102 103
Creating a Migration
--------------------
104

S
Steve Klabnik 已提交
105
### Creating a Standalone Migration
106

107
Migrations are stored as files in the `db/migrate` directory, one for each
V
Vijay Dev 已提交
108
migration class. The name of the file is of the form
109
`YYYYMMDDHHMMSS_create_products.rb`, that is to say a UTC timestamp
V
Vijay Dev 已提交
110 111
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 已提交
112
should match the latter part of the file name. For example
113 114
`20080906120000_create_products.rb` should define class `CreateProducts` and
`20080906120001_add_details_to_products.rb` should define
S
Steve Klabnik 已提交
115 116 117
`AddDetailsToProducts`. Rails uses this timestamp to determine which migration
should be run and in what order, so if you're copying a migration from another
application or generate a file yourself, be aware of its position in the order.
118

S
Steve Klabnik 已提交
119 120
Of course, calculating timestamps is no fun, so Active Record provides a
generator to handle making it for you:
121

P
Prem Sichanugrist 已提交
122
```bash
123
$ rails generate migration AddPartNumberToProducts
124
```
125 126 127

This will create an empty but appropriately named migration:

128
```ruby
129
class AddPartNumberToProducts < ActiveRecord::Migration
130
  def change
131 132
  end
end
133
```
134

J
Jason Noble 已提交
135 136
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
137
appropriate `add_column` and `remove_column` statements will be created.
138

P
Prem Sichanugrist 已提交
139
```bash
140
$ rails generate migration AddPartNumberToProducts part_number:string
141
```
142 143 144

will generate

145
```ruby
146
class AddPartNumberToProducts < ActiveRecord::Migration
147
  def change
148 149 150
    add_column :products, :part_number, :string
  end
end
151
```
152

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
If you'd like to add an index on the new column, you can do that as well:

```bash
$ rails generate migration AddPartNumberToProducts part_number:string:index
```

will generate

```ruby
class AddPartNumberToProducts < ActiveRecord::Migration
  def change
    add_column :products, :part_number, :string
    add_index :products, :part_number
  end
end
```


Similarly, you can generate a migration to remove a column from the command line:
172

P
Prem Sichanugrist 已提交
173
```bash
174
$ rails generate migration RemovePartNumberFromProducts part_number:string
175
```
176 177 178

generates

179
```ruby
180
class RemovePartNumberFromProducts < ActiveRecord::Migration
181 182
  def change
    remove_column :products, :part_number, :string
183 184
  end
end
185
```
186

187
You are not limited to one magically generated column. For example
188

P
Prem Sichanugrist 已提交
189
```bash
190
$ rails generate migration AddDetailsToProducts part_number:string price:decimal
191
```
192 193 194

generates

195
```ruby
196
class AddDetailsToProducts < ActiveRecord::Migration
197
  def change
198 199 200 201
    add_column :products, :part_number, :string
    add_column :products, :price, :decimal
  end
end
202
```
203

204
If the migration name is of the form "CreateXXX" and is
205
followed by a list of column names and types then a migration creating the table
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
XXX with the columns listed will be generated. For example:

```bash
$ rails generate migration CreateProducts name:string part_number:string
```

generates

```ruby
class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.string :part_number
    end
  end
end
```

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

S
Steve Klabnik 已提交
229 230
Also, the generator accepts column type as `references`(also available as
`belongs_to`). For instance
A
Aleksey Magusev 已提交
231

P
Prem Sichanugrist 已提交
232
```bash
A
Aleksey Magusev 已提交
233
$ rails generate migration AddUserRefToProducts user:references
234
```
A
Aleksey Magusev 已提交
235 236 237

generates

238
```ruby
A
Aleksey Magusev 已提交
239 240
class AddUserRefToProducts < ActiveRecord::Migration
  def change
A
Agis Anastasopoulos 已提交
241
    add_reference :products, :user, index: true
A
Aleksey Magusev 已提交
242 243
  end
end
244
```
A
Aleksey Magusev 已提交
245

S
Steve Klabnik 已提交
246 247
This migration will create a `user_id` column and appropriate index.

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
There is also a generator which will produce join tables if `JoinTable` is part of the name:

```bash
rails g migration CreateJoinTableCustomerProduct customer product
```

will produce the following migration:

```ruby
class CreateJoinTableCustomerProduct < ActiveRecord::Migration
  def change
    create_join_table :customers, :products do |t|
      # t.index [:customer_id, :product_id]
      # t.index [:product_id, :customer_id]
    end
  end
end
```

S
Steve Klabnik 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
### Model Generators

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

```bash
$ rails generate model Product name:string description:text
```

will create a migration that looks like this

```ruby
class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end
```

You can append as many column name/type pairs as you want.
A
Aleksey Magusev 已提交
294

295
### Supported Type Modifiers
A
Aleksey Magusev 已提交
296

S
Steve Klabnik 已提交
297 298
You can also specify some options just after the field type between curly
braces. You can use the following modifiers:
A
Aleksey Magusev 已提交
299

300 301 302 303
* `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 已提交
304

305
For instance, running
A
Aleksey Magusev 已提交
306

P
Prem Sichanugrist 已提交
307
```bash
A
Aleksey Magusev 已提交
308
$ rails generate migration AddDetailsToProducts price:decimal{5,2} supplier:references{polymorphic}
309
```
A
Aleksey Magusev 已提交
310 311 312

will produce a migration that looks like this

313
```ruby
A
Aleksey Magusev 已提交
314 315
class AddDetailsToProducts < ActiveRecord::Migration
  def change
A
Agis Anastasopoulos 已提交
316 317
    add_column :products, :price, precision: 5, scale: 2
    add_reference :products, :user, polymorphic: true, index: true
A
Aleksey Magusev 已提交
318 319
  end
end
320
```
A
Aleksey Magusev 已提交
321

322 323
Writing a Migration
-------------------
324

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

328
### Creating a Table
329

S
Steve Klabnik 已提交
330 331 332
The `create_table` method is one of the most fundamental, but most of the time,
will be generated for you from using a model or scaffold generator. A typical
use would be
333

334
```ruby
335 336 337
create_table :products do |t|
  t.string :name
end
338
```
339

340 341
which creates a `products` table with a column called `name` (and as discussed
below, an implicit `id` column).
342

343 344
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
S
Steve Klabnik 已提交
345 346 347
update the corresponding model) or, if you don't want a primary key at all, you
can pass the option `id: false`. If you need to pass database specific options
you can place an SQL fragment in the `:options` option. For example,
348

349
```ruby
A
Agis Anastasopoulos 已提交
350 351
create_table :products, options: "ENGINE=BLACKHOLE" do |t|
  t.string :name, null: false
352
end
353
```
354

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

358
### Creating a Join Table
359

360
Migration method `create_join_table` creates a HABTM join table. A typical use
361 362
would be

363
```ruby
364
create_join_table :products, :categories
365
```
366

S
Steve Klabnik 已提交
367 368 369
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.
370

S
Steve Klabnik 已提交
371 372
You can pass the option `:table_name` with you want to customize the table
name. For example,
373

374
```ruby
A
Agis Anastasopoulos 已提交
375
create_join_table :products, :categories, table_name: :categorization
376
```
377

378
will create a `categorization` table.
379

S
Steve Klabnik 已提交
380 381
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,
382

383
```ruby
A
Agis Anastasopoulos 已提交
384
create_join_table :products, :categories, column_options: {null: true}
385
```
386

S
Steve Klabnik 已提交
387 388
will create the `product_id` and `category_id` with the `:null` option as
`true`.
389

390 391 392 393 394 395 396 397 398 399
`create_join_table` also accepts a block, which you can use to add indices
(which are not created by default) or additional columns:

```ruby
create_join_table :products, :categories do |t|
  t.index :products
  t.index :categories
end
```

400
### Changing Tables
401

402
A close cousin of `create_table` is `change_table`, used for changing existing
S
Steve Klabnik 已提交
403 404
tables. It is used in a similar fashion to `create_table` but the object
yielded to the block knows more tricks. For example
405

406
```ruby
407 408 409 410 411 412
change_table :products do |t|
  t.remove :description, :name
  t.string :part_number
  t.index :part_number
  t.rename :upccode, :upc_code
end
413
```
414

415 416
removes the `description` and `name` columns, creates a `part_number` string
column and adds an index on it. Finally it renames the `upccode` column.
417

418
### When Helpers aren't Enough
419

S
Steve Klabnik 已提交
420 421
If the helpers provided by Active Record aren't enough you can use the `execute`
method to execute arbitrary SQL:
422

423
```ruby
S
Steve Klabnik 已提交
424
Products.connection.execute('UPDATE `products` SET `price`=`free` WHERE 1')
425
```
426

427
For more details and examples of individual methods, check the API documentation.
428
In particular the documentation for
429
[`ActiveRecord::ConnectionAdapters::SchemaStatements`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html)
430
(which provides the methods available in the `change`, `up` and `down` methods),
431
[`ActiveRecord::ConnectionAdapters::TableDefinition`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html)
432
(which provides the methods available on the object yielded by `create_table`)
J
Jason Noble 已提交
433
and
434
[`ActiveRecord::ConnectionAdapters::Table`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html)
435
(which provides the methods available on the object yielded by `change_table`).
436

437
### Using the `change` Method
438

S
Steve Klabnik 已提交
439 440 441 442
The `change` method is the primary way of writing migrations. It works for the
majority of cases, where Active Record knows how to reverse the migration
automatically. Currently, the `change` method supports only these migration
definitions:
443

444 445
* `add_column`
* `add_index`
446
* `add_reference`
447 448
* `add_timestamps`
* `create_table`
449 450 451
* `create_join_table`
* `drop_table` (must supply a block)
* `drop_join_table`  (must supply a block)
452 453 454
* `remove_timestamps`
* `rename_column`
* `rename_index`
455
* `remove_reference`
456
* `rename_table`
457

458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
`change_table` is also reversible, as long as the block does not call `change`,
`change_default` or `remove`.

If you're going to need to use any other methods, you should use `reversible`
or write the `up` and `down` methods instead of using the `change` method.

### Using `reversible`

Complex migrations may require processing that Active Record doesn't know how
to reverse. You can use `reversible` to specify what to do when running a
migration what else to do when reverting it. For example,

```ruby
class ExampleMigration < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.references :category
    end

    reversible do |dir|
      dir.up do
        #add a foreign key
        execute <<-SQL
          ALTER TABLE products
            ADD CONSTRAINT fk_products_categories
            FOREIGN KEY (category_id)
            REFERENCES categories(id)
        SQL
      end
      dir.down do
        execute <<-SQL
          ALTER TABLE products
            DROP FOREIGN KEY fk_products_categories
        SQL
      end
    end

    add_column :users, :home_page_url, :string
    rename_column :users, :email, :email_address
  end
```

500
Using `reversible` will ensure that the instructions are executed in the
501 502 503 504 505 506 507 508 509
right order too. If the previous example migration is reverted,
the `down` block will be run after the `home_page_url` column is removed and
right before the table `products` is dropped.

Sometimes your migration will do something which is just plain irreversible; for
example, it might destroy some data. In such cases, you can raise
`ActiveRecord::IrreversibleMigration` in your `down` block. If someone tries
to revert your migration, an error message will be displayed saying that it
can't be done.
510

511
### Using the `up`/`down` Methods
512

513 514
You can also use the old style of migration using `up` and `down` methods
instead of the `change` method.
S
Steve Klabnik 已提交
515 516 517 518 519 520
The `up` method should describe the transformation you'd like to make to your
schema, and 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
521
made in the `up` method. The example in the `reversible` section is equivalent to:
522

523
```ruby
524
class ExampleMigration < ActiveRecord::Migration
525
  def up
526 527 528
    create_table :products do |t|
      t.references :category
    end
S
Steve Klabnik 已提交
529

L
Lucas Caton 已提交
530
    # add a foreign key
P
Pratik Naik 已提交
531 532 533 534 535 536
    execute <<-SQL
      ALTER TABLE products
        ADD CONSTRAINT fk_products_categories
        FOREIGN KEY (category_id)
        REFERENCES categories(id)
    SQL
S
Steve Klabnik 已提交
537

538 539 540 541
    add_column :users, :home_page_url, :string
    rename_column :users, :email, :email_address
  end

542
  def down
543 544
    rename_column :users, :email_address, :email
    remove_column :users, :home_page_url
S
Steve Klabnik 已提交
545

J
Jason Noble 已提交
546 547 548 549
    execute <<-SQL
      ALTER TABLE products
        DROP FOREIGN KEY fk_products_categories
    SQL
S
Steve Klabnik 已提交
550

551 552 553
    drop_table :products
  end
end
554
```
555

556
If your migration is irreversible, you should raise
557
`ActiveRecord::IrreversibleMigration` from your `down` method. If someone tries
J
Jason Noble 已提交
558 559
to revert your migration, an error message will be displayed saying that it
can't be done.
560

561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
### Reverting Previous Migrations

You can use Active Record's ability to rollback migrations using the `revert` method:

```ruby
require_relative '2012121212_example_migration'

class FixupExampleMigration < ActiveRecord::Migration
  def change
    revert ExampleMigration

    create_table(:apples) do |t|
      t.string :variety
    end
  end
end
```

The `revert` method also accepts a block of instructions to reverse.
This could be useful to revert selected parts of previous migrations.
For example, let's imagine that `ExampleMigration` is committed and it
is later decided it would be best to serialize the product list instead.
One could write:

```ruby
class SerializeProductListMigration < ActiveRecord::Migration
  def change
    add_column :categories, :product_list

    reversible do |dir|
      dir.up do
        # transfer data from Products to Category#product_list
      end
      dir.down do
        # create Products from Category#product_list
      end
    end

    revert do
      # copy-pasted code from ExampleMigration
      create_table :products do |t|
        t.references :category
      end

      reversible do |dir|
        dir.up do
          #add a foreign key
          execute <<-SQL
            ALTER TABLE products
              ADD CONSTRAINT fk_products_categories
              FOREIGN KEY (category_id)
              REFERENCES categories(id)
          SQL
        end
        dir.down do
          execute <<-SQL
            ALTER TABLE products
              DROP FOREIGN KEY fk_products_categories
          SQL
        end
      end

      # The rest of the migration was ok
    end
  end
end
```

The same migration could also have been written without using `revert`
but this would have involved a few more steps: reversing the order
of `create_table` and `reversible`, replacing `create_table`
by `drop_table`, and finally replacing `up` by `down` and vice-versa.
This is all taken care of by `revert`.

635 636
Running Migrations
------------------
637

S
Steve Klabnik 已提交
638
Rails provides a set of Rake tasks to run certain sets of migrations.
639

S
Steve Klabnik 已提交
640
The very first migration related Rake task you will use will probably be
641
`rake db:migrate`. In its most basic form it just runs the `change` or `up`
642 643 644
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.
645

646
Note that running the `db:migrate` also invokes the `db:schema:dump` task, which
1
1334 已提交
647
will update your `db/schema.rb` file to match the structure of your database.
648

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

P
Prem Sichanugrist 已提交
654
```bash
655
$ rake db:migrate VERSION=20080906120000
656
```
657

J
Jason Noble 已提交
658
If version 20080906120000 is greater than the current version (i.e., it is
659 660
migrating upwards), this will run the `change` (or `up`) method
on all migrations up to and
V
Vijay Dev 已提交
661
including 20080906120000, and will not execute any later migrations. If
662
migrating downwards, this will run the `down` method on all the migrations
663
down to, but not including, 20080906120000.
664

665
### Rolling Back
666

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

P
Prem Sichanugrist 已提交
671
```bash
672
$ rake db:rollback
673
```
674

675 676
This will rollback the latest migration, either by reverting the `change`
method or by running the `down` method. If you need to undo
677
several migrations you can provide a `STEP` parameter:
678

P
Prem Sichanugrist 已提交
679
```bash
680
$ rake db:rollback STEP=3
681
```
682

683
will revert the last 3 migrations.
684

685 686
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 已提交
687
if you need to go more than one version back, for example
688

P
Prem Sichanugrist 已提交
689
```bash
690
$ rake db:migrate:redo STEP=3
691
```
692

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

697
### Resetting the Database
698

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

S
Steve Klabnik 已提交
702 703 704 705
NOTE: This is not the same as running all the migrations. It will only use the
contents of the current schema.rb file. If a migration can't be rolled back,
'rake db:reset' may not help you. To find out more about dumping the schema see
'[schema dumping and you](#schema-dumping-and-you).'
706

707
### Running Specific Migrations
708

709 710
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
711 712
the corresponding migration will have its `change`, `up` or `down` method
invoked, for example,
713

P
Prem Sichanugrist 已提交
714
```bash
715
$ rake db:migrate:up VERSION=20080906120000
716
```
717

718 719
will run the 20080906120000 migration by running the `change` method (or the
`up` method). This task will
S
Steve Klabnik 已提交
720 721
first check whether the migration is already performed and will do nothing if
Active Record believes that it has already been run.
722

723 724
### Running Migrations in Different Environments

S
Steve Klabnik 已提交
725 726 727 728
By default running `rake db:migrate` will run in the `development` environment.
To run migrations against another environment you can specify it using the
`RAILS_ENV` environment variable while running the command. For example to run
migrations against the `test` environment you could run:
729 730 731 732 733

```bash
$ rake db:migrate RAILS_ENV=test
```

734
### Changing the Output of Running Migrations
735

J
Jason Noble 已提交
736 737
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
738

P
Prem Sichanugrist 已提交
739
```bash
J
Jason Noble 已提交
740
==  CreateProducts: migrating =================================================
741
-- create_table(:products)
J
Jason Noble 已提交
742 743
   -> 0.0028s
==  CreateProducts: migrated (0.0028s) ========================================
744
```
745

746 747
Several methods are provided in migrations that allow you to control all this:

748 749 750 751 752
| Method               | Purpose
| -------------------- | -------
| suppress_messages    | Takes a block as an argument and suppresses any output 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 block. If the block returns an integer it assumes it is the number of rows affected.
753 754 755

For example, this migration

756
```ruby
757
class CreateProducts < ActiveRecord::Migration
758
  def change
759 760 761 762 763 764 765
    suppress_messages do
      create_table :products do |t|
        t.string :name
        t.text :description
        t.timestamps
      end
    end
S
Steve Klabnik 已提交
766

767
    say "Created a table"
S
Steve Klabnik 已提交
768

769 770
    suppress_messages {add_index :products, :name}
    say "and an index!", true
S
Steve Klabnik 已提交
771

772 773 774 775 776 777
    say_with_time 'Waiting for a while' do
      sleep 10
      250
    end
  end
end
778
```
779 780 781

generates the following output

P
Prem Sichanugrist 已提交
782
```bash
J
Jason Noble 已提交
783 784
==  CreateProducts: migrating =================================================
-- Created a table
785
   -> and an index!
J
Jason Noble 已提交
786 787
-- Waiting for a while
   -> 10.0013s
788
   -> 250 rows
J
Jason Noble 已提交
789
==  CreateProducts: migrated (10.0054s) =======================================
790
```
791

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

S
Steve Klabnik 已提交
795 796 797 798 799 800 801
Changing Existing Migrations
----------------------------

Occasionally you will make a mistake when writing a migration. If you have
already run the migration then you cannot just edit the migration and run the
migration again: Rails thinks it has already run the migration and so will do
nothing when you run `rake db:migrate`. You must rollback the migration (for
802 803
example with `rake db:rollback`), edit your migration and then run
`rake db:migrate` to run the corrected version.
S
Steve Klabnik 已提交
804 805 806 807 808 809 810 811 812

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.

813 814 815 816
The `revert` method can be helpful when writing a new migration to undo
previous migrations in whole or in part
(see [Reverting Previous Migrations](#reverting-previous-migrations) above).

817 818
Using Models in Your Migrations
-------------------------------
819

S
Steve Klabnik 已提交
820 821
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
J
Jason Noble 已提交
822
data. This can be done, but some caution should be observed.
823

J
Jason Noble 已提交
824 825 826
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.
827

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

831 832
Bob goes on vacation.

833
Alice creates a migration for the `products` table which adds a new column and
S
Steve Klabnik 已提交
834
initializes it. She also adds a validation to the `Product` model for the new
J
Jason Noble 已提交
835
column.
836

837
```ruby
838 839 840 841
# db/migrate/20100513121110_add_flag_to_product.rb

class AddFlagToProduct < ActiveRecord::Migration
  def change
J
Jason Noble 已提交
842
    add_column :products, :flag, :boolean
843 844 845
    reversible do |dir|
      dir.up { Product.update_all flag: false }
    end
A
Agis Anastasopoulos 已提交
846
    Product.update_all flag: false
847
  end
848
end
849
```
850

851
```ruby
A
Akira Matsuda 已提交
852
# app/models/product.rb
853 854

class Product < ActiveRecord::Base
855
  validates :flag, :inclusion => { :in => [true, false] }
856
end
857
```
858

J
Jason Noble 已提交
859
Alice adds a second migration which adds and initializes another column to the
860
`products` table and also adds a validation to the `Product` model for the new
J
Jason Noble 已提交
861
column.
862

863
```ruby
864 865 866
# db/migrate/20100515121110_add_fuzz_to_product.rb

class AddFuzzToProduct < ActiveRecord::Migration
867
  def change
868
    add_column :products, :fuzz, :string
869 870 871
    reversible do |dir|
      dir.up { Product.update_all fuzz: 'fuzzy' }
    end
872 873
  end
end
874
```
875

876
```ruby
A
Akira Matsuda 已提交
877
# app/models/product.rb
878

879
class Product < ActiveRecord::Base
880 881
  validates :flag, :inclusion => { :in => [true, false] }
  validates :fuzz, presence: true
882
end
883
```
884

885 886 887 888
Both migrations work for Alice.

Bob comes back from vacation and:

S
Steve Klabnik 已提交
889 890
*   Updates the source - which contains both migrations and the latest version
    of the Product model.
891 892
*   Runs outstanding migrations with `rake db:migrate`, which
    includes the one that updates the `Product` model.
893

J
Jason Noble 已提交
894 895 896
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:
897

898
```
899 900 901 902
rake aborted!
An error has occurred, this and all later migrations canceled:

undefined method `fuzz' for #<Product:0x000001049b14a0>
903
```
904

S
Steve Klabnik 已提交
905 906
A fix for this is to create a local model within the migration. This keeps
Rails from running the validations, so that the migrations run to completion.
907

S
Steve Klabnik 已提交
908
When using a local model, it's a good idea to call
909 910
`Product.reset_column_information` to refresh the `ActiveRecord` cache for the
`Product` model prior to updating data in the database.
911 912 913

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

914
```ruby
915 916
# db/migrate/20100513121110_add_flag_to_product.rb

V
Vijay Dev 已提交
917
class AddFlagToProduct < ActiveRecord::Migration
918 919
  class Product < ActiveRecord::Base
  end
V
Vijay Dev 已提交
920

921
  def change
922
    add_column :products, :flag, :boolean
V
Vijay Dev 已提交
923
    Product.reset_column_information
924 925 926
    reversible do |dir|
      dir.up { Product.update_all flag: false }
    end
927 928
  end
end
929
```
930

931
```ruby
932 933 934 935 936
# db/migrate/20100515121110_add_fuzz_to_product.rb

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

938
  def change
939
    add_column :products, :fuzz, :string
940
    Product.reset_column_information
941 942 943
    reversible do |dir|
      dir.up { Product.update_all fuzz: 'fuzzy' }
    end
944 945
  end
end
946
```
947

948 949 950
There are other ways in which the above example could have gone badly.

For example, imagine that Alice creates a migration that selectively
S
Steve Klabnik 已提交
951
updates the `description` field on certain products. She runs the
952
migration, commits the code, and then begins working on the next feature,
S
Steve Klabnik 已提交
953
which is to add a new column `fuzz` to the products table.
954 955

She creates two migrations for this new feature, one which adds the new
S
Steve Klabnik 已提交
956
column, and a second which selectively updates the `fuzz` column based on
957 958 959 960
other product attributes.

These migrations run just fine, but when Bob comes back from his vacation
and calls `rake db:migrate` to run all the outstanding migrations, he gets a
S
Steve Klabnik 已提交
961 962
subtle bug: The descriptions have defaults, and the `fuzz` column is present,
but `fuzz` is nil on all products.
963

S
Steve Klabnik 已提交
964
The solution is again to use `Product.reset_column_information` before
965 966 967 968
referencing the Product model in a migration, ensuring the Active Record's
knowledge of the table structure is current before manipulating data in those
records.

969 970
Schema Dumping and You
----------------------
971

972
### What are Schema Files for?
973

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

J
Jason Noble 已提交
979 980 981
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.
982

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

J
Jason Noble 已提交
987 988
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 已提交
989 990
frequently spread across several migrations, but the information is nicely
summed up in the schema file. The
991
[annotate_models](https://github.com/ctran/annotate_models) gem automatically
V
Vijay Dev 已提交
992
adds and updates comments at the top of each model summarizing the schema if
J
Jason Noble 已提交
993
you desire that functionality.
994

995
### Types of Schema Dumps
996

S
Steve Klabnik 已提交
997 998 999
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`.
1000

1001
If `:ruby` is selected then the schema is stored in `db/schema.rb`. If you look
S
Steve Klabnik 已提交
1002 1003
at this file you'll find that it looks an awful lot like one very big
migration:
1004

1005
```ruby
1006 1007
ActiveRecord::Schema.define(version: 20080906171750) do
  create_table "authors", force: true do |t|
1008 1009 1010 1011 1012
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

1013
  create_table "products", force: true do |t|
1014
    t.string   "name"
J
Jason Noble 已提交
1015
    t.text "description"
1016 1017
    t.datetime "created_at"
    t.datetime "updated_at"
J
Jason Noble 已提交
1018
    t.string "part_number"
1019 1020
  end
end
1021
```
1022

J
Jason Noble 已提交
1023
In many ways this is exactly what it is. This file is created by inspecting the
1024
database and expressing its structure using `create_table`, `add_index`, and so
J
Jason Noble 已提交
1025
on. Because this is database-independent, it could be loaded into any database
S
Steve Klabnik 已提交
1026 1027
that Active Record supports. This could be very useful if you were to
distribute an application that is able to run against multiple databases.
J
Jason Noble 已提交
1028

1029
There is however a trade-off: `db/schema.rb` cannot express database specific
J
Jason Noble 已提交
1030 1031 1032
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
1033
this, then you should set the schema format to `:sql`.
J
Jason Noble 已提交
1034

S
Steve Klabnik 已提交
1035 1036 1037 1038 1039
Instead of using Active Record's schema dumper, the database's structure will
be dumped using a tool specific to the database (via the `db:structure:dump`
Rake task) into `db/structure.sql`. For example, for PostgreSQL, the `pg_dump`
utility is used. For MySQL, this file will contain the output of `SHOW CREATE
TABLE` for the various tables.
1040

1041 1042 1043
Loading these schemas is simply a question of executing the SQL statements they
contain. By definition, this will create a perfect copy of the database's
structure. Using the `:sql` schema format will, however, prevent loading the
1044
schema into a RDBMS other than the one used to create it.
1045

1046
### Schema Dumps and Source Control
1047

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

1051 1052
Active Record and Referential Integrity
---------------------------------------
1053

J
Jason Noble 已提交
1054 1055 1056 1057 1058
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.

A
Agis Anastasopoulos 已提交
1059
Validations such as `validates :foreign_key, uniqueness: true` are one way in
S
Steve Klabnik 已提交
1060 1061 1062 1063 1064 1065 1066 1067
which models can enforce data integrity. The `:dependent` 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 in the database.

Although Active Record does not provide any tools for working directly with
such features, the `execute` method can be used to execute arbitrary SQL. You
L
Lucas Caton 已提交
1068
could also use some gem like
S
Steve Klabnik 已提交
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
[foreigner](https://github.com/matthuhiggins/foreigner) which add foreign key
support to Active Record (including support for dumping foreign keys in
`db/schema.rb`).

Migrations and Seed Data
------------------------

Some people use migrations to add data to the database:

```ruby
class AddInitialProducts < ActiveRecord::Migration
  def up
    5.times do |i|
      Product.create(name: "Product ##{i}", description: "A product.")
    end
  end

  def down
    Product.delete_all
  end
end
```

However, Rails has a 'seeds' feature that should be used for seeding a database
with initial data. It's a really simple feature: just fill up `db/seeds.rb`
with some Ruby code, and run `rake db:seed`:

```ruby
5.times do |i|
  Product.create(name: "Product ##{i}", description: "A product.")
end
```

This is generally a much cleaner way to set up the database of a blank
application.