2018-07-23 22:29:31 -04:00
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**
2014-12-23 17:32:50 -05:00
2012-11-29 08:30:31 -05:00
Active Record Migrations
========================
2009-02-05 20:57:02 -05:00
2012-11-29 07:27:29 -05:00
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.
2012-11-29 17:25:02 -05:00
After reading this guide, you will know:
2012-11-29 07:27:29 -05:00
2012-11-29 08:14:08 -05:00
* The generators you can use to create them.
* The methods Active Record provides to manipulate your database.
2018-06-29 12:49:05 -04:00
* The rails commands that manipulate migrations and your schema.
2012-11-29 08:14:08 -05:00
* How migrations relate to `schema.rb` .
2012-11-29 07:27:29 -05:00
--------------------------------------------------------------------------------
2012-11-29 14:13:09 -05:00
Migration Overview
------------------
2012-11-29 07:27:29 -05:00
2014-03-26 04:06:31 -04:00
Migrations are a convenient way to
2017-08-22 20:36:38 -04:00
[alter your database schema over time ](https://en.wikipedia.org/wiki/Schema_migration )
2014-03-26 04:06:31 -04:00
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.
2011-12-03 18:48:41 -05:00
2012-11-29 14:13:09 -05:00
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
2012-11-29 07:27:29 -05:00
`db/schema.rb` file to match the up-to-date structure of your database.
2011-12-03 18:48:41 -05:00
2012-11-29 14:13:09 -05:00
Here's an example of a migration:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2015-12-15 01:40:40 -05:00
class CreateProducts < ActiveRecord::Migration [ 5 . 0 ]
2012-11-29 14:13:09 -05:00
def change
2011-12-04 05:59:11 -05:00
create_table :products do |t|
2009-02-05 20:57:02 -05:00
t.string :name
t.text :description
2016-03-03 03:24:04 -05:00
t.timestamps
2009-02-05 20:57:02 -05:00
end
end
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-11-29 14:13:09 -05:00
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.
2012-12-19 14:46:16 -05:00
On databases that support transactions with statements that change the schema,
2012-11-29 14:13:09 -05:00
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.
2009-02-05 20:57:02 -05:00
2013-03-01 05:39:39 -05:00
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.
2012-11-29 14:13:09 -05:00
If you wish for a migration to do something that Active Record doesn't know how
2012-12-19 14:46:16 -05:00
to reverse, you can use `reversible` :
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2015-12-15 01:40:40 -05:00
class ChangeProductsPrice < ActiveRecord::Migration [ 5 . 0 ]
2012-12-19 14:46:16 -05:00
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` :
2012-12-29 11:50:05 -05:00
```ruby
2015-12-15 01:40:40 -05:00
class ChangeProductsPrice < ActiveRecord::Migration [ 5 . 0 ]
2011-04-26 12:33:39 -04:00
def up
2012-11-29 14:13:09 -05:00
change_table :products do |t|
2012-12-19 14:46:16 -05:00
t.change :price, :string
2009-02-05 20:57:02 -05:00
end
end
2012-12-19 14:46:16 -05:00
2011-04-26 12:33:39 -04:00
def down
2012-11-29 14:13:09 -05:00
change_table :products do |t|
2012-12-19 14:46:16 -05:00
t.change :price, :integer
2011-04-26 12:30:08 -04:00
end
end
end
2012-09-01 17:08:06 -04:00
```
2011-04-26 12:30:08 -04:00
2012-11-29 14:13:09 -05:00
Creating a Migration
--------------------
2009-02-05 20:57:02 -05:00
2012-11-29 14:13:09 -05:00
### Creating a Standalone Migration
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
Migrations are stored as files in the `db/migrate` directory, one for each
2011-12-04 05:59:11 -05:00
migration class. The name of the file is of the form
2012-09-01 21:37:59 -04:00
`YYYYMMDDHHMMSS_create_products.rb` , that is to say a UTC timestamp
2011-12-04 05:59:11 -05:00
identifying the migration followed by an underscore followed by the name
of the migration. The name of the migration class (CamelCased version)
2011-12-03 18:48:41 -05:00
should match the latter part of the file name. For example
2012-09-01 21:37:59 -04:00
`20080906120000_create_products.rb` should define class `CreateProducts` and
`20080906120001_add_details_to_products.rb` should define
2012-12-26 15:24:22 -05:00
`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.
2009-02-05 20:57:02 -05:00
2012-11-29 14:13:09 -05:00
Of course, calculating timestamps is no fun, so Active Record provides a
generator to handle making it for you:
2009-02-05 20:57:02 -05:00
2012-09-01 20:45:26 -04:00
```bash
2018-06-26 16:02:51 -04:00
$ rails generate migration AddPartNumberToProducts
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2018-05-11 04:17:53 -04:00
This will create an appropriately named empty migration:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2015-12-15 01:40:40 -05:00
class AddPartNumberToProducts < ActiveRecord::Migration [ 5 . 0 ]
2011-04-26 12:30:08 -04:00
def change
2009-02-05 20:57:02 -05:00
end
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2018-05-11 04:17:53 -04:00
This generator can do much more than append a timestamp to the file name.
Based on naming conventions and additional (optional) arguments it can
also start fleshing out the migration.
If the migration name is of the form "AddColumnToTable" or
"RemoveColumnFromTable" and is followed by a list of column names and
types then a migration containing the appropriate `add_column` and
`remove_column` statements will be created.
2009-02-05 20:57:02 -05:00
2012-09-01 20:45:26 -04:00
```bash
2018-06-26 16:02:51 -04:00
$ rails generate migration AddPartNumberToProducts part_number:string
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
will generate
2012-09-01 17:08:06 -04:00
```ruby
2015-12-15 01:40:40 -05:00
class AddPartNumberToProducts < ActiveRecord::Migration [ 5 . 0 ]
2011-04-26 12:30:08 -04:00
def change
2009-02-05 20:57:02 -05:00
add_column :products, :part_number, :string
end
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2013-04-17 17:16:47 -04:00
If you'd like to add an index on the new column, you can do that as well:
```bash
2018-06-26 16:02:51 -04:00
$ rails generate migration AddPartNumberToProducts part_number:string:index
2013-04-17 17:16:47 -04:00
```
will generate
```ruby
2015-12-15 01:40:40 -05:00
class AddPartNumberToProducts < ActiveRecord::Migration [ 5 . 0 ]
2013-04-17 17:16:47 -04:00
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:
2009-02-05 20:57:02 -05:00
2012-09-01 20:45:26 -04:00
```bash
2018-06-26 16:02:51 -04:00
$ rails generate migration RemovePartNumberFromProducts part_number:string
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
generates
2012-09-01 17:08:06 -04:00
```ruby
2015-12-15 01:40:40 -05:00
class RemovePartNumberFromProducts < ActiveRecord::Migration [ 5 . 0 ]
2012-12-19 14:46:16 -05:00
def change
2013-11-13 03:02:11 -05:00
remove_column :products, :part_number, :string
2009-02-05 20:57:02 -05:00
end
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2013-09-28 01:04:01 -04:00
You are not limited to one magically generated column. For example:
2009-02-05 20:57:02 -05:00
2012-09-01 20:45:26 -04:00
```bash
2018-06-26 16:02:51 -04:00
$ rails generate migration AddDetailsToProducts part_number:string price:decimal
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
generates
2012-09-01 17:08:06 -04:00
```ruby
2015-12-15 01:40:40 -05:00
class AddDetailsToProducts < ActiveRecord::Migration [ 5 . 0 ]
2011-04-26 12:30:08 -04:00
def change
2009-02-05 20:57:02 -05:00
add_column :products, :part_number, :string
add_column :products, :price, :decimal
end
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-26 14:02:28 -05:00
If the migration name is of the form "CreateXXX" and is
2013-03-01 05:39:39 -05:00
followed by a list of column names and types then a migration creating the table
2012-12-26 14:02:28 -05:00
XXX with the columns listed will be generated. For example:
```bash
2018-06-26 16:02:51 -04:00
$ rails generate migration CreateProducts name:string part_number:string
2012-12-26 14:02:28 -05:00
```
generates
```ruby
2015-12-15 01:40:40 -05:00
class CreateProducts < ActiveRecord::Migration [ 5 . 0 ]
2012-12-26 14:02:28 -05:00
def change
create_table :products do |t|
t.string :name
t.string :part_number
end
end
end
```
2011-12-03 18:48:41 -05:00
As always, what has been generated for you is just a starting point. You can add
2011-12-04 05:59:11 -05:00
or remove from it as you see fit by editing the
2012-10-17 09:15:55 -04:00
`db/migrate/YYYYMMDDHHMMSS_add_details_to_products.rb` file.
2009-02-05 20:57:02 -05:00
2016-10-30 23:28:34 -04:00
Also, the generator accepts column type as `references` (also available as
2013-09-28 01:04:01 -04:00
`belongs_to` ). For instance:
2012-07-08 09:20:43 -04:00
2012-09-01 20:45:26 -04:00
```bash
2018-06-26 16:02:51 -04:00
$ rails generate migration AddUserRefToProducts user:references
2012-09-01 17:08:06 -04:00
```
2012-07-08 09:20:43 -04:00
generates
2012-09-01 17:08:06 -04:00
```ruby
2015-12-15 01:40:40 -05:00
class AddUserRefToProducts < ActiveRecord::Migration [ 5 . 0 ]
2012-07-08 09:20:43 -04:00
def change
2016-07-16 05:21:51 -04:00
add_reference :products, :user, foreign_key: true
2012-07-08 09:20:43 -04:00
end
end
2012-09-01 17:08:06 -04:00
```
2012-07-08 09:20:43 -04:00
2016-04-18 01:56:21 -04:00
This migration will create a `user_id` column and appropriate index.
2019-03-05 22:00:45 -05:00
For more `add_reference` options, visit the [API documentation ](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_reference ).
2012-11-29 14:13:09 -05:00
2012-12-29 12:11:45 -05:00
There is also a generator which will produce join tables if `JoinTable` is part of the name:
```bash
2018-06-26 16:02:51 -04:00
$ rails g migration CreateJoinTableCustomerProduct customer product
2012-12-29 12:11:45 -05:00
```
will produce the following migration:
```ruby
2015-12-15 01:40:40 -05:00
class CreateJoinTableCustomerProduct < ActiveRecord::Migration [ 5 . 0 ]
2012-12-29 12:11:45 -05:00
def change
create_join_table :customers, :products do |t|
# t.index [:customer_id, :product_id]
# t.index [:product_id, :customer_id]
end
end
end
```
2012-11-29 14:13:09 -05:00
### 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
2013-09-28 01:04:01 -04:00
adding these columns will also be created. For example, running:
2012-11-29 14:13:09 -05:00
```bash
2018-06-26 16:02:51 -04:00
$ rails generate model Product name:string description:text
2012-11-29 14:13:09 -05:00
```
will create a migration that looks like this
```ruby
2015-12-15 01:40:40 -05:00
class CreateProducts < ActiveRecord::Migration [ 5 . 0 ]
2012-11-29 14:13:09 -05:00
def change
create_table :products do |t|
t.string :name
t.text :description
2016-03-02 19:23:15 -05:00
t.timestamps
2012-11-29 14:13:09 -05:00
end
end
end
```
You can append as many column name/type pairs as you want.
2012-07-08 09:20:43 -04:00
2014-06-10 04:21:15 -04:00
### Passing Modifiers
2012-07-08 09:20:43 -04:00
2014-06-10 04:21:15 -04:00
Some commonly used [type modifiers ](#column-modifiers ) can be passed directly on
the command line. They are enclosed by curly braces and follow the field type:
2014-06-10 01:38:08 -04:00
2013-09-28 01:04:01 -04:00
For instance, running:
2012-07-08 09:20:43 -04:00
2012-09-01 20:45:26 -04:00
```bash
2018-06-26 16:02:51 -04:00
$ rails generate migration AddDetailsToProducts 'price:decimal{5,2}' supplier:references{polymorphic}
2012-09-01 17:08:06 -04:00
```
2012-07-08 09:20:43 -04:00
will produce a migration that looks like this
2012-09-01 17:08:06 -04:00
```ruby
2015-12-15 01:40:40 -05:00
class AddDetailsToProducts < ActiveRecord::Migration [ 5 . 0 ]
2012-07-08 09:20:43 -04:00
def change
2013-09-24 12:27:21 -04:00
add_column :products, :price, :decimal, precision: 5, scale: 2
2016-07-16 05:21:51 -04:00
add_reference :products, :supplier, polymorphic: true
2012-07-08 09:20:43 -04:00
end
end
2012-09-01 17:08:06 -04:00
```
2012-07-08 09:20:43 -04:00
2014-06-10 04:21:15 -04:00
TIP: Have a look at the generators help output for further details.
2012-09-01 17:25:58 -04:00
Writing a Migration
-------------------
2009-02-05 20:57:02 -05:00
2011-12-03 18:48:41 -05:00
Once you have created your migration using one of the generators it's time to
get to work!
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Creating a Table
2009-02-05 20:57:02 -05:00
2012-11-29 14:13:09 -05:00
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
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2009-02-05 20:57:02 -05:00
create_table :products do |t|
t.string :name
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
which creates a `products` table with a column called `name` (and as discussed
below, an implicit `id` column).
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
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
2012-11-29 14:13:09 -05:00
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
2013-09-28 01:04:01 -04:00
you can place an SQL fragment in the `:options` option. For example:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-16 05:26:26 -05:00
create_table :products, options: "ENGINE=BLACKHOLE" do |t|
t.string :name, null: false
2009-02-05 20:57:02 -05:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2017-11-18 06:22:28 -05:00
will append `ENGINE=BLACKHOLE` to the SQL statement used to create the table.
2009-02-24 07:29:25 -05:00
2016-01-03 13:13:53 -05:00
Also you can pass the `:comment` option with any description for the table
that will be stored in database itself and can be viewed with database administration
tools, such as MySQL Workbench or PgAdmin III. It's highly recommended to specify
comments in migrations for applications with large databases as it helps people
to understand data model and generate documentation.
2016-04-18 01:56:21 -04:00
Currently only the MySQL and PostgreSQL adapters support comments.
2016-01-03 13:13:53 -05:00
2012-09-01 17:25:58 -04:00
### Creating a Join Table
2012-01-27 11:57:43 -05:00
2015-07-30 17:04:03 -04:00
The migration method `create_join_table` creates an HABTM (has and belongs to
many) join table. A typical use would be:
2012-01-27 11:57:43 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-01-27 11:57:43 -05:00
create_join_table :products, :categories
2012-09-01 17:08:06 -04:00
```
2012-01-27 11:57:43 -05:00
2012-11-29 14:13:09 -05:00
which creates a `categories_products` table with two columns called
`category_id` and `product_id` . These columns have the option `:null` set to
2013-06-13 15:28:11 -04:00
`false` by default. This can be overridden by specifying the `:column_options`
2015-07-30 17:04:03 -04:00
option:
2012-01-27 11:57:43 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2015-07-30 17:04:03 -04:00
create_join_table :products, :categories, column_options: { null: true }
2012-09-01 17:08:06 -04:00
```
2012-01-27 11:57:43 -05:00
2015-07-30 17:04:03 -04:00
By default, the name of the join table comes from the union of the first two
arguments provided to create_join_table, in alphabetical order.
To customize the name of the table, provide a `:table_name` option:
2012-01-27 11:57:43 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2013-06-13 15:28:11 -04:00
create_join_table :products, :categories, table_name: :categorization
2012-09-01 17:08:06 -04:00
```
2012-01-27 11:57:43 -05:00
2015-07-30 17:04:03 -04:00
creates a `categorization` table.
2012-01-27 11:57:43 -05:00
2013-02-20 16:18:06 -05:00
`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|
2013-06-21 04:27:55 -04:00
t.index :product_id
t.index :category_id
2013-02-20 16:18:06 -05:00
end
```
2012-09-01 17:25:58 -04:00
### Changing Tables
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
A close cousin of `create_table` is `change_table` , used for changing existing
2012-11-29 14:13:09 -05:00
tables. It is used in a similar fashion to `create_table` but the object
2013-09-28 01:04:01 -04:00
yielded to the block knows more tricks. For example:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2009-02-05 20:57:02 -05:00
change_table :products do |t|
t.remove :description, :name
t.string :part_number
t.index :part_number
t.rename :upccode, :upc_code
end
2012-09-01 17:08:06 -04:00
```
2011-08-16 22:59:36 -04:00
2012-09-01 21:37:59 -04:00
removes the `description` and `name` columns, creates a `part_number` string
column and adds an index on it. Finally it renames the `upccode` column.
2009-02-05 20:57:02 -05:00
2014-06-01 08:55:11 -04:00
### Changing Columns
2014-06-01 17:02:04 -04:00
Like the `remove_column` and `add_column` Rails provides the `change_column`
migration method.
2014-06-01 08:55:11 -04:00
```ruby
change_column :products, :part_number, :text
```
2014-06-01 17:02:04 -04:00
This changes the column `part_number` on products table to be a `:text` field.
2015-05-04 16:25:10 -04:00
Note that `change_column` command is irreversible.
2014-06-01 08:55:11 -04:00
2014-06-01 17:02:04 -04:00
Besides `change_column` , the `change_column_null` and `change_column_default`
2015-05-04 16:25:10 -04:00
methods are used specifically to change a not null constraint and default
values of a column.
2014-06-01 08:55:11 -04:00
```ruby
change_column_null :products, :name, false
2015-05-04 16:25:10 -04:00
change_column_default :products, :approved, from: true, to: false
2014-06-01 08:55:11 -04:00
```
2014-06-01 17:02:04 -04:00
This sets `:name` field on products to a `NOT NULL` column and the default
2015-05-04 16:25:10 -04:00
value of the `:approved` field from true to false.
2014-06-01 08:55:11 -04:00
2018-03-12 07:39:24 -04:00
NOTE: You could also write the above `change_column_default` migration as
2015-05-04 16:25:10 -04:00
`change_column_default :products, :approved, false` , but unlike the previous
example, this would make your migration irreversible.
2014-06-20 15:52:31 -04:00
2014-06-10 04:21:15 -04:00
### Column Modifiers
Column modifiers can be applied when creating or changing a column:
* `limit` Sets the maximum size of the `string/text/binary/integer` fields.
2014-06-27 09:09:10 -04:00
* `precision` Defines the precision for the `decimal` fields, representing the
total number of digits in the number.
* `scale` Defines the scale for the `decimal` fields, representing the
number of digits after the decimal point.
2014-06-10 04:21:15 -04:00
* `polymorphic` Adds a `type` column for `belongs_to` associations.
* `null` Allows or disallows `NULL` values in the column.
2014-06-27 09:09:10 -04:00
* `default` Allows to set a default value on the column. Note that if you
are using a dynamic value (such as a date), the default will only be calculated
the first time (i.e. on the date the migration is applied).
2016-01-03 13:13:53 -05:00
* `comment` Adds a comment for the column.
2014-06-10 04:21:15 -04:00
Some adapters may support additional options; see the adapter specific API docs
for further information.
2016-10-20 14:32:57 -04:00
NOTE: `null` and `default` cannot be specified via command line.
2014-06-12 02:42:00 -04:00
### Foreign Keys
While it's not required you might want to add foreign key constraints to
[guarantee referential integrity ](#active-record-and-referential-integrity ).
```ruby
add_foreign_key :articles, :authors
```
This adds a new foreign key to the `author_id` column of the `articles`
2014-10-24 10:59:16 -04:00
table. The key references the `id` column of the `authors` table. If the
2019-03-06 16:35:52 -05:00
column names cannot be derived from the table names, you can use the
2014-06-12 02:42:00 -04:00
`:column` and `:primary_key` options.
Rails will generate a name for every foreign key starting with
2015-06-29 19:54:57 -04:00
`fk_rails_` followed by 10 characters which are deterministically
2015-06-11 20:35:08 -04:00
generated from the `from_table` and `column` .
2014-06-12 02:42:00 -04:00
There is a `:name` option to specify a different name if needed.
NOTE: Active Record only supports single column foreign keys. `execute` and
2015-01-29 17:37:38 -05:00
`structure.sql` are required to use composite foreign keys. See
[Schema Dumping and You ](#schema-dumping-and-you ).
2014-06-12 02:42:00 -04:00
Removing a foreign key is easy as well:
```ruby
# let Active Record figure out the column name
remove_foreign_key :accounts, :branches
# remove foreign key for a specific column
remove_foreign_key :accounts, column: :owner_id
# remove foreign key by name
remove_foreign_key :accounts, name: :special_fk_name
```
2012-12-07 16:31:27 -05:00
### When Helpers aren't Enough
2009-02-05 20:57:02 -05:00
2012-11-29 14:13:09 -05:00
If the helpers provided by Active Record aren't enough you can use the `execute`
method to execute arbitrary SQL:
2012-03-02 20:59:23 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2015-04-01 10:03:41 -04:00
Product.connection.execute("UPDATE products SET price = 'free' WHERE 1=1")
2012-09-01 17:08:06 -04:00
```
2012-03-02 20:59:23 -05:00
2012-10-01 20:49:04 -04:00
For more details and examples of individual methods, check the API documentation.
2012-08-21 23:37:47 -04:00
In particular the documentation for
2019-03-05 22:00:45 -05:00
[`ActiveRecord::ConnectionAdapters::SchemaStatements` ](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html )
2012-12-19 14:46:16 -05:00
(which provides the methods available in the `change` , `up` and `down` methods),
2019-03-05 22:00:45 -05:00
[`ActiveRecord::ConnectionAdapters::TableDefinition` ](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html )
2012-09-01 21:37:59 -04:00
(which provides the methods available on the object yielded by `create_table` )
2011-12-03 18:48:41 -05:00
and
2019-03-05 22:00:45 -05:00
[`ActiveRecord::ConnectionAdapters::Table` ](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html )
2012-09-01 21:37:59 -04:00
(which provides the methods available on the object yielded by `change_table` ).
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
### Using the `change` Method
2011-04-26 12:30:08 -04:00
2012-11-29 14:13:09 -05:00
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:
2011-04-26 12:30:08 -04:00
2015-08-30 07:28:55 -04:00
* add_column
* add_foreign_key
* add_index
* add_reference
* add_timestamps
* change_column_default (must supply a :from and :to option)
* change_column_null
* create_join_table
* create_table
* disable_extension
* drop_join_table
* drop_table (must supply a block)
* enable_extension
* remove_column (must supply a type)
* remove_foreign_key (must supply a second table)
* remove_index
* remove_reference
* remove_timestamps
* rename_column
* rename_index
* rename_table
2011-04-26 12:30:08 -04:00
2012-12-19 14:46:16 -05:00
`change_table` is also reversible, as long as the block does not call `change` ,
`change_default` or `remove` .
2015-03-24 08:06:28 -04:00
`remove_column` is reversible if you supply the column type as the third
argument. Provide the original column options too, otherwise Rails can't
recreate the column exactly when rolling back:
```ruby
2018-06-29 12:04:15 -04:00
remove_column :posts, :slug, :string, null: false, default: ''
2015-03-24 08:06:28 -04:00
```
2012-12-19 14:46:16 -05:00
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
2015-05-14 00:05:48 -04:00
migration and what else to do when reverting it. For example:
2012-12-19 14:46:16 -05:00
```ruby
2015-12-15 01:40:40 -05:00
class ExampleMigration < ActiveRecord::Migration [ 5 . 0 ]
2012-12-19 14:46:16 -05:00
def change
2014-06-12 02:42:00 -04:00
create_table :distributors do |t|
t.string :zipcode
2012-12-19 14:46:16 -05:00
end
reversible do |dir|
dir.up do
2014-06-12 02:42:00 -04:00
# add a CHECK constraint
2012-12-19 14:46:16 -05:00
execute < < -SQL
2014-06-12 02:42:00 -04:00
ALTER TABLE distributors
ADD CONSTRAINT zipchk
CHECK (char_length(zipcode) = 5) NO INHERIT;
2012-12-19 14:46:16 -05:00
SQL
end
dir.down do
execute < < -SQL
2014-06-12 02:42:00 -04:00
ALTER TABLE distributors
DROP CONSTRAINT zipchk
2012-12-19 14:46:16 -05:00
SQL
end
end
add_column :users, :home_page_url, :string
rename_column :users, :email, :email_address
end
2014-04-15 03:57:09 -04:00
end
2012-12-19 14:46:16 -05:00
```
2013-02-19 11:56:36 -05:00
Using `reversible` will ensure that the instructions are executed in the
2012-12-19 14:46:16 -05:00
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
2014-06-12 02:42:00 -04:00
right before the table `distributors` is dropped.
2012-12-19 14:46:16 -05:00
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.
2011-04-26 12:30:08 -04:00
2012-09-01 21:37:59 -04:00
### Using the `up`/`down` Methods
2009-02-05 20:57:02 -05:00
2012-12-19 14:46:16 -05:00
You can also use the old style of migration using `up` and `down` methods
instead of the `change` method.
2012-11-29 14:13:09 -05:00
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
2015-05-14 00:05:48 -04:00
is wise to perform the transformations in precisely the reverse order they were
2012-12-19 14:46:16 -05:00
made in the `up` method. The example in the `reversible` section is equivalent to:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2015-12-15 01:40:40 -05:00
class ExampleMigration < ActiveRecord::Migration [ 5 . 0 ]
2011-04-26 12:33:39 -04:00
def up
2014-06-12 02:42:00 -04:00
create_table :distributors do |t|
t.string :zipcode
2009-02-05 20:57:02 -05:00
end
2012-11-29 14:13:09 -05:00
2014-06-12 02:42:00 -04:00
# add a CHECK constraint
2009-02-24 07:29:25 -05:00
execute < < -SQL
2014-06-12 02:42:00 -04:00
ALTER TABLE distributors
ADD CONSTRAINT zipchk
CHECK (char_length(zipcode) = 5);
2009-02-24 07:29:25 -05:00
SQL
2012-11-29 14:13:09 -05:00
2009-02-05 20:57:02 -05:00
add_column :users, :home_page_url, :string
rename_column :users, :email, :email_address
end
2011-04-26 12:33:39 -04:00
def down
2009-02-05 20:57:02 -05:00
rename_column :users, :email_address, :email
remove_column :users, :home_page_url
2012-11-29 14:13:09 -05:00
2011-12-03 18:48:41 -05:00
execute < < -SQL
2014-06-12 02:42:00 -04:00
ALTER TABLE distributors
DROP CONSTRAINT zipchk
2011-12-03 18:48:41 -05:00
SQL
2012-11-29 14:13:09 -05:00
2014-06-12 02:42:00 -04:00
drop_table :distributors
2009-02-05 20:57:02 -05:00
end
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-19 14:46:16 -05:00
If your migration is irreversible, you should raise
2012-09-01 21:37:59 -04:00
`ActiveRecord::IrreversibleMigration` from your `down` method. If someone tries
2011-12-03 18:48:41 -05:00
to revert your migration, an error message will be displayed saying that it
can't be done.
2009-02-05 20:57:02 -05:00
2012-12-19 14:46:16 -05:00
### Reverting Previous Migrations
You can use Active Record's ability to rollback migrations using the `revert` method:
```ruby
2015-08-24 08:21:44 -04:00
require_relative '20121212123456_example_migration'
2012-12-19 14:46:16 -05:00
2015-12-15 01:40:40 -05:00
class FixupExampleMigration < ActiveRecord::Migration [ 5 . 0 ]
2012-12-19 14:46:16 -05:00
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
2014-06-12 02:42:00 -04:00
is later decided it would be best to use Active Record validations,
in place of the `CHECK` constraint, to verify the zipcode.
2012-12-19 14:46:16 -05:00
```ruby
2015-12-15 01:40:40 -05:00
class DontUseConstraintForZipcodeValidationMigration < ActiveRecord::Migration [ 5 . 0 ]
2012-12-19 14:46:16 -05:00
def change
revert do
# copy-pasted code from ExampleMigration
reversible do |dir|
dir.up do
2014-06-12 02:42:00 -04:00
# add a CHECK constraint
2012-12-19 14:46:16 -05:00
execute < < -SQL
2014-06-12 02:42:00 -04:00
ALTER TABLE distributors
ADD CONSTRAINT zipchk
CHECK (char_length(zipcode) = 5);
2012-12-19 14:46:16 -05:00
SQL
end
dir.down do
execute < < -SQL
2014-06-12 02:42:00 -04:00
ALTER TABLE distributors
DROP CONSTRAINT zipchk
2012-12-19 14:46:16 -05:00
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` .
2015-01-29 17:37:38 -05:00
NOTE: If you want to add check constraints like in the examples above,
you will have to use `structure.sql` as dump method. See
[Schema Dumping and You ](#schema-dumping-and-you ).
2012-09-01 17:25:58 -04:00
Running Migrations
------------------
2009-02-05 20:57:02 -05:00
2018-06-29 12:49:05 -04:00
Rails provides a set of rails commands to run certain sets of migrations.
2011-12-03 21:19:17 -05:00
2018-06-29 12:49:05 -04:00
The very first migration related rails command you will use will probably be
2015-12-18 07:01:05 -05:00
`rails db:migrate` . In its most basic form it just runs the `change` or `up`
2011-12-03 21:19:17 -05:00
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.
2009-02-05 20:57:02 -05:00
2018-06-29 12:49:05 -04:00
Note that running the `db:migrate` command also invokes the `db:schema:dump` command, which
2012-12-03 08:01:27 -05:00
will update your `db/schema.rb` file to match the structure of your database.
2009-02-05 20:57:02 -05:00
2011-12-03 18:48:41 -05:00
If you specify a target version, Active Record will run the required migrations
2012-12-19 14:46:16 -05:00
(change, up, down) until it has reached the specified version. The version
2011-12-04 05:59:11 -05:00
is the numerical prefix on the migration's filename. For example, to migrate
2013-09-28 01:04:01 -04:00
to version 20080906120000 run:
2009-02-05 20:57:02 -05:00
2012-09-01 20:45:26 -04:00
```bash
2018-06-26 16:02:51 -04:00
$ rails db:migrate VERSION=20080906120000
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2011-12-03 18:48:41 -05:00
If version 20080906120000 is greater than the current version (i.e., it is
2012-12-19 14:46:16 -05:00
migrating upwards), this will run the `change` (or `up` ) method
on all migrations up to and
2011-12-04 05:59:11 -05:00
including 20080906120000, and will not execute any later migrations. If
2012-09-01 21:37:59 -04:00
migrating downwards, this will run the `down` method on all the migrations
2011-12-03 21:20:40 -05:00
down to, but not including, 20080906120000.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Rolling Back
2009-02-05 20:57:02 -05:00
2012-08-21 23:37:47 -04:00
A common task is to rollback the last migration. For example, if you made a
2011-12-03 18:48:41 -05:00
mistake in it and wish to correct it. Rather than tracking down the version
2013-09-28 01:04:01 -04:00
number associated with the previous migration you can run:
2009-02-05 20:57:02 -05:00
2012-09-01 20:45:26 -04:00
```bash
2018-06-26 16:02:51 -04:00
$ rails db:rollback
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-19 14:46:16 -05:00
This will rollback the latest migration, either by reverting the `change`
method or by running the `down` method. If you need to undo
2012-09-01 21:37:59 -04:00
several migrations you can provide a `STEP` parameter:
2009-02-05 20:57:02 -05:00
2012-09-01 20:45:26 -04:00
```bash
2018-06-26 16:02:51 -04:00
$ rails db:rollback STEP=3
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-19 14:46:16 -05:00
will revert the last 3 migrations.
2009-02-05 20:57:02 -05:00
2018-06-29 12:49:05 -04:00
The `db:migrate:redo` command is a shortcut for doing a rollback and then migrating
back up again. As with the `db:rollback` command, you can use the `STEP` parameter
2013-09-28 01:04:01 -04:00
if you need to go more than one version back, for example:
2009-02-05 20:57:02 -05:00
2012-09-01 20:45:26 -04:00
```bash
2018-06-26 16:02:51 -04:00
$ rails db:migrate:redo STEP=3
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2018-06-29 12:49:05 -04:00
Neither of these rails commands do anything you could not do with `db:migrate` . They
2011-12-03 18:48:41 -05:00
are simply more convenient, since you do not need to explicitly specify the
version to migrate to.
2009-02-05 20:57:02 -05:00
2013-08-29 12:18:07 -04:00
### Setup the Database
2018-06-29 12:49:05 -04:00
The `rails db:setup` command will create the database, load the schema, and initialize
2013-08-30 00:10:30 -04:00
it with the seed data.
2013-08-29 12:18:07 -04:00
2012-09-01 17:25:58 -04:00
### Resetting the Database
2011-12-03 21:21:08 -05:00
2018-06-29 12:49:05 -04:00
The `rails db:reset` command will drop the database and set it up again. This is
2016-01-19 06:08:56 -05:00
functionally equivalent to `rails db:drop db:setup` .
2009-02-05 20:57:02 -05:00
2012-11-29 14:13:09 -05:00
NOTE: This is not the same as running all the migrations. It will only use the
2015-10-15 16:37:11 -04:00
contents of the current `db/schema.rb` or `db/structure.sql` file. If a migration can't be rolled back,
2015-12-18 07:01:05 -05:00
`rails db:reset` may not help you. To find out more about dumping the schema see
2013-09-16 12:33:14 -04:00
[Schema Dumping and You ](#schema-dumping-and-you ) section.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Running Specific Migrations
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
If you need to run a specific migration up or down, the `db:migrate:up` and
2018-06-29 12:49:05 -04:00
`db:migrate:down` commands will do that. Just specify the appropriate version and
2012-12-19 14:46:16 -05:00
the corresponding migration will have its `change` , `up` or `down` method
2013-09-28 01:04:01 -04:00
invoked, for example:
2009-02-05 20:57:02 -05:00
2012-09-01 20:45:26 -04:00
```bash
2018-06-26 16:02:51 -04:00
$ rails db:migrate:up VERSION=20080906120000
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-19 14:46:16 -05:00
will run the 20080906120000 migration by running the `change` method (or the
2018-06-29 12:49:05 -04:00
`up` method). This command will
2012-11-29 14:13:09 -05:00
first check whether the migration is already performed and will do nothing if
Active Record believes that it has already been run.
2009-02-05 20:57:02 -05:00
2012-10-01 20:49:04 -04:00
### Running Migrations in Different Environments
2018-06-26 16:02:51 -04:00
By default running `rails db:migrate` will run in the `development` environment.
2012-11-29 14:13:09 -05:00
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:
2012-10-01 20:49:04 -04:00
```bash
2018-06-26 16:02:51 -04:00
$ rails db:migrate RAILS_ENV=test
2012-10-01 20:49:04 -04:00
```
2012-09-01 17:25:58 -04:00
### Changing the Output of Running Migrations
2009-02-05 20:57:02 -05:00
2011-12-03 18:48:41 -05:00
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
2009-02-05 20:57:02 -05:00
2012-09-01 20:45:26 -04:00
```bash
2011-12-03 18:48:41 -05:00
== CreateProducts: migrating =================================================
2009-02-05 20:57:02 -05:00
-- create_table(:products)
2011-12-03 18:48:41 -05:00
-> 0.0028s
== CreateProducts: migrated (0.0028s) ========================================
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2011-12-03 21:22:55 -05:00
Several methods are provided in migrations that allow you to control all this:
2012-09-02 13:08:06 -04:00
| 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.
2009-02-05 20:57:02 -05:00
2013-09-28 01:04:01 -04:00
For example, this migration:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2015-12-15 01:40:40 -05:00
class CreateProducts < ActiveRecord::Migration [ 5 . 0 ]
2011-04-26 12:30:08 -04:00
def change
2009-02-05 20:57:02 -05:00
suppress_messages do
create_table :products do |t|
t.string :name
t.text :description
2016-03-03 03:24:04 -05:00
t.timestamps
2009-02-05 20:57:02 -05:00
end
end
2012-11-29 14:13:09 -05:00
2009-02-05 20:57:02 -05:00
say "Created a table"
2012-11-29 14:13:09 -05:00
2009-02-05 20:57:02 -05:00
suppress_messages {add_index :products, :name}
say "and an index!", true
2012-11-29 14:13:09 -05:00
2009-02-05 20:57:02 -05:00
say_with_time 'Waiting for a while' do
sleep 10
250
end
end
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
generates the following output
2012-09-01 20:45:26 -04:00
```bash
2011-12-03 18:48:41 -05:00
== CreateProducts: migrating =================================================
-- Created a table
2009-02-05 20:57:02 -05:00
-> and an index!
2011-12-03 18:48:41 -05:00
-- Waiting for a while
-> 10.0013s
2009-02-05 20:57:02 -05:00
-> 250 rows
2011-12-03 18:48:41 -05:00
== CreateProducts: migrated (10.0054s) =======================================
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2015-12-18 07:01:05 -05:00
If you want Active Record to not output anything, then running `rails db:migrate
2012-09-01 21:37:59 -04:00
VERBOSE=false` will suppress all output.
2009-02-05 20:57:02 -05:00
2012-11-29 14:13:09 -05:00
Changing Existing Migrations
----------------------------
Occasionally you will make a mistake when writing a migration. If you have
2016-02-05 00:34:30 -05:00
already run the migration, then you cannot just edit the migration and run the
2012-11-29 14:13:09 -05:00
migration again: Rails thinks it has already run the migration and so will do
2015-12-18 07:01:05 -05:00
nothing when you run `rails db:migrate` . You must rollback the migration (for
2018-06-26 16:02:51 -04:00
example with `rails db:rollback` ), edit your migration, and then run
2015-12-18 07:01:05 -05:00
`rails db:migrate` to run the corrected version.
2012-11-29 14:13:09 -05:00
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.
2012-12-19 14:46:16 -05:00
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).
2012-09-01 17:25:58 -04:00
Schema Dumping and You
----------------------
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### What are Schema Files for?
2009-02-05 20:57:02 -05:00
2011-12-03 18:48:41 -05:00
Migrations, mighty as they may be, are not the authoritative source for your
2018-04-19 15:41:01 -04:00
database schema. Your database remains the authoritative source. By default,
Rails generates `db/schema.rb` which attempts to capture the current state of
your database schema.
2009-02-05 20:57:02 -05:00
2018-04-19 15:41:01 -04:00
It tends to be faster and less error prone to create a new instance of your
application's database by loading the schema file via `rails db:schema:load`
2018-07-30 10:48:42 -04:00
than it is to replay the entire migration history.
[Old migrations ](#old-migrations ) may fail to apply correctly if those
migrations use changing external dependencies or rely on application code which
evolves separately from your migrations.
2009-02-05 20:57:02 -05:00
2011-12-03 18:48:41 -05:00
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
2011-12-04 05:59:11 -05:00
frequently spread across several migrations, but the information is nicely
2018-04-19 15:41:01 -04:00
summed up in the schema file.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Types of Schema Dumps
2009-02-05 20:57:02 -05:00
2018-04-19 15:41:01 -04:00
The format of the schema dump generated by Rails is controlled by the
`config.active_record.schema_format` setting in `config/application.rb` . By
default, the format is `:ruby` , but can also be set to `:sql` .
2009-02-05 20:57:02 -05:00
2016-02-05 00:34:30 -05:00
If `:ruby` is selected, then the schema is stored in `db/schema.rb` . If you look
2018-04-19 15:41:01 -04:00
at this file you'll find that it looks an awful lot like one very big migration:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2019-03-26 20:57:33 -04:00
ActiveRecord::Schema.define(version: 2008_09_06_171750) do
2012-09-07 14:27:08 -04:00
create_table "authors", force: true do |t|
2009-02-05 20:57:02 -05:00
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
2012-09-07 14:27:08 -04:00
create_table "products", force: true do |t|
2009-02-05 20:57:02 -05:00
t.string "name"
2016-11-06 18:43:59 -05:00
t.text "description"
2009-02-05 20:57:02 -05:00
t.datetime "created_at"
t.datetime "updated_at"
2016-11-06 18:43:59 -05:00
t.string "part_number"
2009-02-05 20:57:02 -05:00
end
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2011-12-03 18:48:41 -05:00
In many ways this is exactly what it is. This file is created by inspecting the
2012-09-01 21:37:59 -04:00
database and expressing its structure using `create_table` , `add_index` , and so
2018-04-19 15:41:01 -04:00
on.
`db/schema.rb` cannot express everything your database may support such as
triggers, sequences, stored procedures, check constraints, etc. While migrations
may use `execute` to create database constructs that are not supported by the
Ruby migration DSL, these constructs may not be able to be reconstituted by the
schema dumper. If you are using features like these, you should set the schema
format to `:sql` in order to get an accurate schema file that is useful to
create new database instances.
When the schema format is set to `:sql` , the database structure will be dumped
using a tool specific to the database into `db/structure.sql` . For example, for
PostgreSQL, the `pg_dump` utility is used. For MySQL and MariaDB, this file will
contain the output of `SHOW CREATE TABLE` for the various tables.
2018-04-24 12:51:34 -04:00
To load the schema from `db/structure.sql` , run `rails db:structure:load` .
2018-04-19 15:41:01 -04:00
Loading this file is done by executing the SQL statements it contains. By
definition, this will create a perfect copy of the database's structure.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Schema Dumps and Source Control
2009-02-05 20:57:02 -05:00
2018-04-19 15:41:01 -04:00
Because schema files are commonly used to create new databases, it is strongly
recommended that you check your schema file into source control.
2009-02-05 20:57:02 -05:00
2018-04-19 15:41:01 -04:00
Merge conflicts can occur in your schema file when two branches modify schema.
To resolve these conflicts run `rails db:migrate` to regenerate the schema file.
2014-05-14 17:43:57 -04:00
2012-09-01 17:25:58 -04:00
Active Record and Referential Integrity
---------------------------------------
2009-02-05 20:57:02 -05:00
2011-12-03 18:48:41 -05:00
The Active Record way claims that intelligence belongs in your models, not in
2014-06-12 02:42:00 -04:00
the database. As such, features such as triggers or constraints,
2011-12-03 18:48:41 -05:00
which push some of that intelligence back into the database, are not heavily
used.
2012-11-16 05:26:26 -05:00
Validations such as `validates :foreign_key, uniqueness: true` are one way in
2012-11-29 14:13:09 -05:00
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
2014-06-12 02:42:00 -04:00
with [foreign key constraints ](#foreign-keys ) in the database.
Although Active Record does not provide all the tools for working directly with
such features, the `execute` method can be used to execute arbitrary SQL.
2012-11-29 14:13:09 -05:00
Migrations and Seed Data
------------------------
2016-10-20 14:32:24 -04:00
The main purpose of Rails' migration feature is to issue commands that modify the
schema using a consistent process. Migrations can also be used
to add or modify data. This is useful in an existing database that can't be destroyed
and recreated, such as a production database.
2012-11-29 14:13:09 -05:00
```ruby
2015-12-15 01:40:40 -05:00
class AddInitialProducts < ActiveRecord::Migration [ 5 . 0 ]
2012-11-29 14:13:09 -05:00
def up
5.times do |i|
Product.create(name: "Product ##{i}", description: "A product.")
end
end
def down
Product.delete_all
end
end
```
2016-10-20 14:32:24 -04:00
To add initial data after a database is created, Rails has a built-in
'seeds' feature that makes the process quick and easy. This is especially
useful when reloading the database frequently in development and test environments.
It's easy to get started with this feature: just fill up `db/seeds.rb` with some
2015-12-18 07:01:05 -05:00
Ruby code, and run `rails db:seed` :
2012-11-29 14:13:09 -05:00
```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.
2018-07-30 10:48:42 -04:00
Old Migrations
--------------
2018-08-12 08:08:07 -04:00
The `db/schema.rb` or `db/structure.sql` is a snapshot of the current state of your
2018-07-30 10:48:42 -04:00
database and is the authoritative source for rebuilding that database. This
makes it possible to delete old migration files.
When you delete migration files in the `db/migrate/` directory, any environment
2018-08-12 08:08:07 -04:00
where `rails db:migrate` was run when those files still existed will hold a reference
2018-07-30 10:48:42 -04:00
to the migration timestamp specific to them inside an internal Rails database
table named `schema_migrations` . This table is used to keep track of whether
migrations have been executed in a specific environment.
2018-08-12 08:08:07 -04:00
If you run the `rails db:migrate:status` command, which displays the status
2018-07-30 10:48:42 -04:00
(up or down) of each migration, you should see `********** NO FILE **********`
displayed next to any deleted migration file which was once executed on a
2018-08-12 08:08:07 -04:00
specific environment but can no longer be found in the `db/migrate/` directory.