![](/img/trans.png)
[英]Why is this migration irreversible? (change_table, rename, text)
[英]Is it possible to invoke change_table from command line with ActiveRecord migrations?
通過在遷移名稱中指定關鍵字“ Create”,可以從命令行在遷移中調用create_table語法:
rails g migration CreateMyTables name:string
這將創建具有以下內容的遷移:
class CreateMyTables < ActiveRecord::Migration
def change
create_table :my_tables do |t|
t.string :name
end
end
end
我想使用“ Change”關鍵字來完成相同操作。 因此,從命令行運行:
rails g migration ChangeMyTables user:references
這就是我得到的:
class ChangeMyTables < ActiveRecord::Migration
def change
end
end
這是我所期望的:
class ChangeMyTables < ActiveRecord::Migration
def change
change_table :my_tables do |t|
t.references :user, index: true
end
end
end
有一種方法可以從命令行添加引用列:
rails g migration AddUserToMyTable user:references
注意 :要將列添加到表中,我們使用約定Add[column]To[table]
重命名遷移。
結果將類似於:
class AddUserToMyTable < ActiveRecord::Migration[5.2]
def change
add_reference :my_tables, :user, foreign_key: true
end
end
注意: foreign_key: true
將為您創建索引。
了解有關add_reference的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.