1、Generate migrations
l You can use the “ruby script/generate model model-name” command to generate model and the corresponding migration file.
l You can also generate a migration on its own command:ruby script/generate migration migration-name
2、Running Migrations
rake db:migrate [VERSION=23]
3、API of ActiveRecord::Migration class
l Column Types
The common options of column:
:null=>true or false(If false,the underlying column has a not null constraint added)
:limit=>size(Requests a maximum column length (:string, :text, :binary or :integer columns only))
:default=>value
l add_column
# Adds a new column to the named table.
# See TableDefinition#column for details of the options you can use.
def add_column(table_name, column_name, type, options = {})
#.....
end
example:
add_column :orders,:name,:string,:limit=>100,:null=>false
add_column :orders, :age, :integer
add_column :orders, :ship_class, :string, :limit => 15, :default => 'priority'
add_column :orders, :price, :decimal, :precision => 8, :scale => 2
add_column :meter, :reading, :decimal, :precision => 24, :scale => 0
l remove_column
def remove_column(table_name, column_name)
#....
end
example:
remove_column :products,:price
l rename_column
def rename_column(table, column, new_column_name)
execute "EXEC sp_rename '#{table}.#{column}', '#{new_column_name}'"
end
example:
rename_column :orders, :e_mail, :customer_email
l change_column
Changes the column’s definition according to the new options.
l create_table
options for create_table
:force=>false or true(If you specify true,the migration will drop an existing table of the same name before creating the new one)
:temporary=>true or false(if youo specify true,the migration will create a temporary table)
:options=>”XXX”
options=>”auto_increment=10000”
example:
create_table :tickets,:options=>”auto_increment=10000” do |t|
t.column :column_name,:column_type
…….
end
l drop_table
l rename_table
rename_table(name, new_name)
l add_index:define an index
add_index(table_name, column_name, options = {})
l remove_index
l primary_key
example:
create_table :tickets, :primary_key => :number do |t|
t.column :created_at, :timestamp
t.column :description, :text
end
Tables with no primary key
create_table :authors_books, :id => false do |t|
t.column :author_id, :integer, :null => false
t.column :book_id, :integer, :null => false
end
4、Using Native SQL
You can use “execute” method to execute native sql.For example:
execute “alter table line_items add constraint fk_line_item_products foreign key (product_id) references products(id)”
In this example you use ‘alter’ command to add a foreign key for line_items table.