== Creating A Migration == === Creating a model === 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 adding those will also be created. For example, running `ruby script/generate model Product name:string description:text` will create a migration that looks like this [source, ruby] ----------------------- class CreateProducts < ActiveRecord::Migration def self.up create_table :products do |t| t.string :name t.text :description t.timestamps end end def self.down drop_table :products end end ----------------------- You can append as many column name/type pairs as you want. By default `t.timestamps` (which creates the `updated_at` and `created_at` columns that are automatically populated by Active Record) will be added for you. === Creating a standalone migration === If you are creating migrations for other purposes (for example to add a column to an existing table) then you can use the migration generator: `ruby script/generate migration AddPartNumberToProducts` This will create an empty but appropriately named migration: [source, ruby] ----------------------- class AddPartNumberToProducts < ActiveRecord::Migration def self.up end def self.down end end ----------------------- If the migration name is of the form AddXXXToYYY or RemoveXXXFromY and is followed by a list of column names and types then a migration containing the appropriate add and remove column statements will be created. `ruby script/generate migration AddPartNumberToProducts part_number:string` will generate [source, ruby] ----------------------- class AddPartNumberToProducts < ActiveRecord::Migration def self.up add_column :products, :part_number, :string end def self.down remove_column :products, :part_number end end ----------------------- Similarly, `ruby script/generate migration RemovePartNumberFromProducts part_number:string` generates [source, ruby] ----------------------- class RemovePartNumberFromProducts < ActiveRecord::Migration def self.up remove_column :products, :part_number end def self.down add_column :products, :part_number, :string end end ----------------------- You are not limited to one magically generated column, for example `ruby script/generate migration AddDetailsToProducts part_number:string price:decimal` generates [source, ruby] ----------------------- class AddDetailsToProducts < ActiveRecord::Migration def self.up add_column :products, :part_number, :string add_column :products, :price, :decimal end def self.down remove_column :products, :price remove_column :products, :part_number end end ----------------------- As always, what has been generated for you is just a starting point. You can add or remove from it as you see fit.