有几种写法,最早就是add remove了
class AddSsl < ActiveRecord::Migration def up add_column :accounts, :ssl_enabled, :boolean, :default => 1 end def down remove_column :accounts, :ssl_enabled endend
这个有个显著问题,字段值没了。那么
rails g migration change_date_format_in_my_tableclass ChangeDateFormatInMyTable < ActiveRecord::Migration def self.up change_column :my_table, :my_column, :datetime end def self.down change_column :my_table, :my_column, :date endend
或者
change_table :table_name do |t| t.change :column_name, :column_type, {options}endclass 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 endend
还有一些
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`" endendclass 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 endend
先知三日,富贵十年。