且构网

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

在 Rails 迁移中向现有表添加列

更新时间:2022-05-19 07:57:39

如果你已经运行了你的原始迁移(在编辑之前),那么你需要生成一个新的迁移(rails generate migration add_email_to_users email:string 会解决问题).它将创建一个包含行的迁移文件:add_column :users, email, string然后执行 rake db:migrate 它将运行新迁移,创建新列.

If you have already run your original migration (before editing it), then you need to generate a new migration (rails generate migration add_email_to_users email:string will do the trick). It will create a migration file containing line: add_column :users, email, string Then do a rake db:migrate and it'll run the new migration, creating the new column.

如果您还没有运行原始迁移,您可以像尝试一样对其进行编辑.您的迁移代码几乎完美:您只需要完全删除 add_column 行(该代码试图在创建表之前向表中添加一列,并且您的表创建代码已经更新为包括 t.string :email.

If you have not yet run the original migration you can just edit it, like you're trying to do. Your migration code is almost perfect: you just need to remove the add_column line completely (that code is trying to add a column to a table, before the table has been created, and your table creation code has already been updated to include a t.string :email anyway).