Kevin Pang
Kevin Pang

Reputation: 41442

Updating models in rails / migrations

Let's say I used the following command to create a "User" model:

script/generate model User username:string

This creates the user.rb file along with the migration rb file to create the Users table. Now, I want to add an email column to my User model. What's the best way to do that? Do I do it manually and write the migration file by hand or is there a shortcut for doing it? If I write the migration by hand, do I have to name it the same way as the previous migration script (with a timestamp in front) to guarantee that it runs after the previous migration?

Upvotes: 9

Views: 7413

Answers (3)

Garfield
Garfield

Reputation: 1247

Don't worry about the timestamp. It will be generated automatically. You can do a

rails generate migration add_email_to_user email:string

This would automatically create a migration file which would look like this:

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

  def self.down
    remove_column :email
  end
end

the file would have the timestamp in the format YYYYMMDDHHMMSS (For Rails 2.1 and above) appended in front of the filename.

Upvotes: 6

Jey
Jey

Reputation:

Well you can do two things:

1) If you haven't deployed this anywhere yet, or you don't mind dumping the db and running your migrations again, then modify the file. Remove the tables from your db, and run db:migrate. Easy to do this in development.

2) If this app is in production, or you don't want to drop all your tables. Then create a new migration file. Then in this new migration add/modify/drop the column. Then run db:migrate and the new changes will take effect in your table. This is the best practice.

As for naming your migration, timestamps are used because rails will create a table that keeps track of the latest migrations ran. For this, it is better to use the timestamps. But if you choose, you can use your own convention instead of timestamps. Maybe name them 001_migration.rb, 002_migration.rb, etc.

Hope that helps.

Upvotes: 1

Bryan Ash
Bryan Ash

Reputation: 4489

The Guide has information about generating migrations. If you use the rails generator, it will create correctly named files:

ruby script/generate migration AddEmailToUser email:string

Upvotes: 3

Related Questions