我有一个用户模型,它需要一个:email列(我忘记在初始脚手架期间添加该列)。

我打开迁移文件并添加t.string:email,执行rake db:migrate,并得到一个NoMethodError。然后我加了一行

add_column :users, :email, :string

再次rake db:migrate,再次NoMethodError。我是不是漏了一步?

编辑:这是迁移文件。

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

当前回答

你也可以

rake db:rollback

如果您没有向表中添加任何数据。然后通过向迁移文件中添加电子邮件列来编辑迁移文件,然后调用

rake db:migrate

如果您的系统中安装了3.1以上的rails,这将工作。

更简单的方法是让迁移文件中的更改保持原样。 使用

$rake db:migrate:redo

这将回滚上一次迁移并再次迁移。

其他回答

有时,rails生成add_email_to_users email:string生成这样的迁移

class AddEmailToUsers < ActiveRecord::Migration[5.0]
  def change
  end
end

在这种情况下,你必须手动修改一个add_column:

class AddEmailToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :email, :string
  end
end

然后运行rake db:migrate

在终端上使用此命令:

rails generate migration add_fieldname_to_tablename fieldname:string

and

rake db:migrate

要运行此迁移

如果您的表已经存在,您也可以使用force: true强制到表中的列。

例子:

ActiveRecord::Schema.define(version: 20080906171750) do
  create_table "authors", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
end

您可以通过回滚上一次迁移

rake db:rollback STEP=1

或回滚此特定的迁移

rake db:migrate:down VERSION=<YYYYMMDDHHMMSS>

编辑文件,然后再次运行rake db:mirgate。

你也可以这样做。 Rails迁移add_column_to_users email:字符串

然后rake db:migrate 同时在用户控制器中添加:email属性;

欲了解更多详情,请访问http://guides.rubyonrails.org/active_record_migrations.html