Roman
Roman

Reputation: 10403

How does the migration work in Rails?

This is a newbie question. Is the migration (rake db:migrate) feature something that one would using during development or it's strictly a production tool for bringing the database up to date?

Upvotes: 1

Views: 807

Answers (2)

Jakub Arnold
Jakub Arnold

Reputation: 87260

Ideally you want to use migrations only during development, and then load schema and seed the database in production. In reality, they'll allow you to make some changes and then deploy to production without any harm done.

Migrations allow you to work in iterations even on your database. You don't have to worry about forgetting to add something. When you start, just create the table as you think it's right, and you can fix it with another migration later. That's basically the idea. It takes away the one db script rules them all kind of thing.

A little example, if you have a User model with username and password and you need to add an email field, simply do this

rails generate migration AddEmailToUser # this is a convention, but you can name it however you want

class AddEmailToUser < ActiveRecord::Migration
  def change
    add_column :users, :email, :string
  end
end

the change method will work both ways, when you apply the migration, and also when you need to revert it. It's kind of a neat Rails 3.1 magic.

The old version of migrations would look like this

class AddEmailToUser < ActiveRecord::Migration
  def up
    add_column :users, :email, :string
  end

  def down
    remove_column :users, :email
  end
end

Once you've added the migration, just run rake db:migrate and everything should work just fine. A big advantage of migrations is that if you manually mess up your database, you can easily just do

rake db:drop
rake db:create
rake db:migrate

or

rake db:migrate:reset # this might not work if you messed up your migrations

And you have the correct version of the database created

Upvotes: 1

Adrian Serafin
Adrian Serafin

Reputation: 7725

Migrations keep track of changes in your database schema. All changes with it (renaming column, changing tables, adding indexes etc.) should be done via migration. Thanks to that is really easy to deploy changes across multiple production servers.

Upvotes: 0

Related Questions