migration小抄

Migration小抄

资源

官方Guides: Active Record Migration

migration文件的命名规则

YYYYMMDDHHMMSS_create_products.rb
rails会自动在前面加上年月日小时分钟秒
这个是为了保持migration的唯一性与准确的先后顺序

AddXXXToYYY与RemoveXXXFromYYY

增加或删除栏位(string, integer,decimal)

rails会针对这两种格式的命令,来快速帮你填充migration文件里的内容
rails g migration AddPartNumberToProducts part_number:string:index
=> 会生成

class AddPartNumberToProducts < ActiveRecord::Migration[5.0]
    def  change
        add_column :products, :part_number, :string
        add_index :products, :part_number 
    end
end
增加references

rails g migration AddUserRefToProducts user:references
=>

class AddUserRefToProducts < ActiveRecord::Migration[5.0]
    def  change
        add_reference :products, :user, foreign_key: true
    end
end

migrate以后,查看schema
[image:9121264D-DCC3-4781-B52B-0B910DFDFEE3-318-000008B3DDFCECE9/DF0F63C6-CEA5-47AF-B1C1-A86614098413.png]
生成了一个user_id
This migration will create a user_id column and appropriate index. For more add_reference options, visit the API documentation.

删除一个model

  1. rails g migration drop_a_model
  2. drop_table :model_names
  3. rake db:migrate

删除一个栏位

remove_column :model_names, :column_name

更改栏位的默认值

change_column_default(table_name, column_name, default)

给栏位增加index

add_index :table_name, column_name

Rollback

ruby on rails - How to rollback a specific migration? - Stack Overflow

rake db:rollback STEP=1

Debug in migration

mysql - How do I test or debug my migration scripts in rails? - Stack Overflow