[英]Is it possible to invoke change_table from command line with ActiveRecord migrations?
It is possible to invoke a create_table syntax in a migration from command line by specifying the keyword 'Create' in the migration name: 通过在迁移名称中指定关键字“ Create”,可以从命令行在迁移中调用create_table语法:
rails g migration CreateMyTables name:string
This will create a migration with the following content: 这将创建具有以下内容的迁移:
class CreateMyTables < ActiveRecord::Migration
def change
create_table :my_tables do |t|
t.string :name
end
end
end
I would like to accomplish the same but with the 'Change' keyword. 我想使用“ Change”关键字来完成相同操作。 So from the command line I would run:
因此,从命令行运行:
rails g migration ChangeMyTables user:references
This is what I got: 这就是我得到的:
class ChangeMyTables < ActiveRecord::Migration
def change
end
end
This is what I would expect: 这是我所期望的:
class ChangeMyTables < ActiveRecord::Migration
def change
change_table :my_tables do |t|
t.references :user, index: true
end
end
end
There is a way to add the reference column from command line: 有一种方法可以从命令行添加引用列:
rails g migration AddUserToMyTable user:references
Note : to add the column to the table we use the convention Add[column]To[table]
for renaming the migration. 注意 :要将列添加到表中,我们使用约定
Add[column]To[table]
重命名迁移。
The result will be similar to: 结果将类似于:
class AddUserToMyTable < ActiveRecord::Migration[5.2]
def change
add_reference :my_tables, :user, foreign_key: true
end
end
Note: foreign_key: true
will create the index for you. 注意:
foreign_key: true
将为您创建索引。
Learn more about add_reference . 了解有关add_reference的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.