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.
There is a special syntactic shortcut to generate migrations that add fields to a table.
rails generate migration add_fieldname_to_tablename fieldname:string
Running migration:
where MyNewMigration is the name of your migration. The generator will create an empty migration filetimestamp_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.
rails generate migration add_fieldname_to_tablename fieldname:string
class AddFieldnameToTablename < ActiveRecord::Migration
def change
add_column :tablenames, :field, :string
end
end
To run migrations against the currently configured database, use
rake
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 task, 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
rake
db:migrate 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. rake db:migrate
STEP=2
will rollback the latest two migrations.For more detail : Active Record Migration
No comments:
Post a Comment