# change 方法Rails 用于匹配迁移名称的两个模式分别是: add_xxx_to_xxxTable
和 remove_xxx_from_xxxTable
, 其中 xxx
的值会被忽略掉,迁移名称之后的字段名和类型列表才是 Rails 获取字段信息的地方
添加字段 bin/rails generate migration add_quantity_to_line_items quantity:integer
生成的迁移文件如下:
class AddQuantityToLineItems < ActiveRecord:: Migration[ 7.0 ] def change add_column :line_items , :quantity , :integer end end
移除字段(和添加字段类似) bin/rails g migration remove_quantity_from_line_items quantity:integer
生成的迁移文件如下:
class RemoveQuantityFromLineItems < ActiveRecord:: Migration[ 7.0 ] def change remove_column :line_items , :quantity , :integer end end
可以使用 up
和 down
方法以传统风格编写迁移而不使用 change
方法。up
方法用于描述对数据库模式所做的改变, down
方法用于撤销 up
方法所做的改变。 换句话说,如果调用 up
方法之后紧接着调用 down
方法,数据库模式不会发生任何改变。 例如用 up
方法创建数据表,就应该用 down
方法删除这个数据表。 在 down
方法中撤销迁移时,明智的做法是按照和 up
方法中操作相反的顺序执行操作。
# up 方法用于对数据库模式做修改 执行 bin/rails db:migrate
命令时会被调用执行
bin/rails g migration something
添加 up 方法
class Something < ActiveRecord:: Migration[ 7.0 ] def up create_table :people do | t| t. string :name t. integer :age t. timestamps end end end
bin/rails db:migrate:status database: db/development.sqlite3 Status Migration ID Migration Name -------------------------------------------------- up 20240316032753 Create products up 20240320055343 Create carts up 20240320060656 Create line items up 20240323132057 Add quantity to line items up 20240323133840 Combine items in cart down 20240325092635 Something
此时数据库中还没有 people 这张表,执行迁移后,就会生成
bin/rails db:migrate == 20240325092635 Something: migrating == == == == == == == == == == == == == == == == == == == == -- create_table( :people) -> 0 .0022s == 20240325092635 Something: migrated ( 0 .0023s) == == == == == == == == == == == == == == == =
执行迁移后,查看迁移状态,发现变为 up 状态了
bin/rails db:migrate:status database: db/development.sqlite3 Status Migration ID Migration Name -------------------------------------------------- up 20240316032753 Create products up 20240320055343 Create carts up 20240320060656 Create line items up 20240323132057 Add quantity to line items up 20240323133840 Combine items in cart up 20240325092635 Something
# down 方法用于撤销之前的 up 操作对数据库模式的修改 执行 bin/rails db:rollback
命令时会被调用执行
class Something < ActiveRecord:: Migration[ 7.0 ] ... def down drop_table :people end end
撤销之前的建表操作
bin/rails db:rollback == 20240325092635 Something: reverting == == == == == == == == == == == == == == == == == == == == -- drop_table( :people) -> 0 .0017s == 20240325092635 Something: reverted ( 0 .0017s) == == == == == == == == == == == == == == == =
再次查看迁移状态,发现变为 down 状态了
bin/rails db:migrate:status database: db/development.sqlite3 Status Migration ID Migration Name -------------------------------------------------- up 20240316032753 Create products up 20240320055343 Create carts up 20240320060656 Create line items up 20240323132057 Add quantity to line items up 20240323133840 Combine items in cart down 20240325092635 Something