在 Rails 迁移中向现有表添加列 [英] Adding a column to an existing table in a Rails migration
问题描述
我有一个需要 :email
列的用户模型(我忘记在初始脚手架期间添加该列).
I have a Users model which needs an :email
column (I forgot to add that column during the initial scaffold).
我打开了迁移文件并添加了t.string :email
,做了rake db:migrate
,得到了一个NoMethodError
.然后我添加了一行
I opened the migration file and added t.string :email
, did rake db:migrate
, and got a NoMethodError
. Then I added the line
add_column :users, :email, :string
再次rake db:migrate
,再次NoMethodError
.我在这里错过了一步吗?
again rake db:migrate
, again NoMethodError
. Am I missing a step here?
这是迁移文件.
class CreateUsers < ActiveRecord::Migration
def self.up
add_column :users, :email, :string
create_table :users do |t|
t.string :username
t.string :email
t.string :crypted_password
t.string :password_salt
t.string :persistence_token
t.timestamps
end
end
def self.down
drop_table :users
end
end
推荐答案
如果你已经运行了你的原始迁移(在编辑之前),那么你需要生成一个新的迁移(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).
这篇关于在 Rails 迁移中向现有表添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!