有几种写法,最早就是add remove了
class AddSsl < ActiveRecord::Migration
def up
add_column :accounts, :ssl_enabled, :boolean, :default => 1
end
def down
remove_column :accounts, :ssl_enabled
end
end
这个有个显著问题,字段值没了。
那么
rails g migration change_date_format_in_my_table
class ChangeDateFormatInMyTable < ActiveRecord::Migration
def self.up
change_column :my_table, :my_column, :datetime
end
def self.down
change_column :my_table, :my_column, :date
end
end
或者
change_table :table_name do |t|
t.change :column_name, :column_type, {options}
end
class ChangeDataTypeForWidgetCount < ActiveRecord::Migration
def self.up
change_table :widgets do |t|
t.change :count, :float
end
end
def self.down
change_table :widgets do |t|
t.change :count, :integer
end
end
end
还有一些
rename_column(table_name, column_name, new_column_name)
add_index(table_name, column_names, options)
class MakeJoinUnique < ActiveRecord::Migration
def up
execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
end
def down
execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
end
end
class AddPeopleSalary < ActiveRecord::Migration
def up
add_column :people, :salary, :integer
Person.reset_column_information
Person.find(:all).each do |p|
p.update_attribute :salary, SalaryCalculator.compute(p)
end
end
end