Migrations can manage the evolution of a schema used by several physical databases. It's a solution to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to push that change to other developers and to the production server. With migrations, you can describe the transformations in self-contained classes that can be checked into version control systems and executed against another database that might be one, two, or five versions behind.
Adds a new foreign key. Fromtable is the table with the key column, totable contains the referenced primary key. The foreign key will be named after the following pattern: fkrails.identifier is a 10 character long string which is deterministically generated from the fromtable and column.A custom name can be specified with the:name option. If you shuddered in recognition when reading that, then you know what the safe way to do this is: create the column without foreignkey: true; then use PostgreSQL's ALTER TABLE ADD CONSTRAINT with the NOT VALID flag, which will update the catalogs but not actually attempt to verify that the data in the column are currently valid; then, finally.
Example of a simple migration:
This migration will add a boolean flag to the accounts table and remove it if you're backing out of the migration. It shows how all migrations have two methods
up and down that describes the transformations required to implement or remove the migration. These methods can consist of both the migration specific methods like add_column and remove_column , but may also contain regular Ruby code for generating data needed for the transformations.
Example of a more complex migration that also needs to initialize data:
This migration first adds the
system_settings table, then creates the very first row in it using the Active Record model that relies on the table. It also uses the more advanced create_table syntax where you can specify a complete table schema in one block call.
Available transformationsCreation
Modification
Deletion
Irreversible transformations
Some transformations are destructive in a manner that cannot be reversed. Migrations of that kind should raise an
ActiveRecord::IrreversibleMigration exception in their down method.
Running migrations from within Rails
The Rails package has several tools to help create and apply migrations.
To generate a new migration, you can use
where MyNewMigration is the name of your migration. The generator will create an empty migration file
timestamp_my_new_migration.rb in the db/migrate/ directory where timestamp is the UTC formatted date and time that the migration was generated.
There is a special syntactic shortcut to generate migrations that add fields to a table.
This will generate the file
timestamp_add_fieldname_to_tablename.rb , which will look like this:
To run migrations against the currently configured database, use
rails db:migrate . This will update the database by running all of the pending migrations, creating the schema_migrations table (see “About the schema_migrations table” section below) if missing. It will also invoke the db:schema:dump command, which will update your db/schema.rb file to match the structure of your database.
To roll the database back to a previous migration version, use
rails db:rollback VERSION=X where X is the version to which you wish to downgrade. Alternatively, you can also use the STEP option if you wish to rollback last few migrations. rails db:rollback STEP=2 will rollback the latest two migrations.
If any of the migrations throw an
ActiveRecord::IrreversibleMigration exception, that step will fail and you'll have some manual work to do.
Database support
Migrations are currently supported in MySQL, PostgreSQL, SQLite, SQL Server, and Oracle (all supported databases except DB2).
More examples
Not all migrations change the schema. Some just fix the data:
Others remove columns when they migrate up instead of down:
And sometimes you need to do something in SQL not abstracted directly by migrations:
Using a model after changing its table
Sometimes you'll want to add a column in a migration and populate it immediately after. In that case, you'll need to make a call to
Base#reset_column_information in order to ensure that the model has the latest column data from after the new column was added. Example:
Controlling verbosity
By default, migrations will describe the actions they are taking, writing them to the console as they happen, along with benchmarks describing how long each step took.
You can quiet them down by setting ActiveRecord::Migration.verbose = false.
You can also insert your own messages and benchmarks by using the
say_with_time method:
The phrase “Updating salaries…” would then be printed, along with the benchmark for the block when the block completes.
Timestamped Migrations
By default, Rails generates migrations that look like:
The prefix is a generation timestamp (in UTC).
If you'd prefer to use numeric prefixes, you can turn timestamped migrations off by setting:
In application.rb.
Reversible Migrations
Reversible migrations are migrations that know how to go
down for you. You simply supply the up logic, and the Migration system figures out how to execute the down commands for you.
To define a reversible migration, define the
change method in your migration like this:
This migration will create the horses table for you on the way up, and automatically figure out how to drop the table on the way down.
Some commands cannot be reversed. If you care to define how to move up and down in these cases, you should define the
up and down methods as before.
If a command cannot be reversed, an
ActiveRecord::IrreversibleMigration exception will be raised when the migration is moving down.
For a list of commands that are reversible, please see
ActiveRecord::Migration::CommandRecorder .
Transactional Migrations
If the database adapter supports DDL transactions, all migrations will automatically be wrapped in a transaction. There are queries that you can't execute inside a transaction though, and for these situations you can turn the automatic transactions off.
Remember that you can still open your own transactions, even if you are in a
Migration with self.disable_ddl_transaction! .
Methods
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
December 2020
Categories |