且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ruby on Rails:向现有数据库添加列

更新时间:2023-11-30 15:57:04

如Speransky建议的那样,您永远不要修改旧的迁移文件.而是应创建一个新迁移,以添加所需的列.例如,在这种情况下,您将在应用程序中运行以下命令以创建新的迁移:

As Speransky suggested, you should never modify old migration files. Rather you should create a new migration that adds the desired column. For instance, in this case you would run the following command in your app to create the new migration:

rails generate migration AddListIdColumnToIdeas list_id:integer

然后Rails会自动生成迁移文件,剩下要做的就是运行rake db:migrate.

And Rails would generate the migration file automatically and the only thing left to do is run rake db:migrate.

如果您坚持修改旧的迁移文件,则可以像以前一样添加该列,然后运行以下命令:

If you insist on modifying the old migration file, you can add the column as you did and run the following:

rake db:drop
rake db:create
rake db:migrate

这将销毁您当前的数据库,创建一个新数据库并运行所有迁移(其中将包括您的新列).

Which will destroy your current database, create a new one and run all the migrations (which will include your new column).