首页 > 解决方案 > 修复已删除表(包括模型)的现有迁移的未初始化常量错误

问题描述

我有一个一年前创建的汽车表,现在需要重命名为汽车表。

车表迁移

class AddDataToCarsModel < ActiveRecord::Migration[5.0]
  def change
    # some cars are missing their created timestamp
    Car.where(created_at: nil).each do |car|
      date = Time.zone.now
      car.update_attribute(:created_at, date)
    end
  end
end

车辆表重命名迁移

class RenameCarsToVehicles < ActiveRecord::Migration[5.1]
  def change
    rename_table :cars, :vehicles
  end
end

但是,当删除当前数据库并运行迁移时,我收到uninitialized constant AddDataToCarsModel::Car错误,因为我已经删除了作为其中一部分的汽车模型。这些情况的最佳做法是什么?是否值得运行一年前创建的旧迁移并对其进行更新?我们该如何处理这些情况?

谢谢您的帮助。

标签: ruby-on-railsruby-on-rails-5rails-migrations

解决方案


作为迁移的修复,您可以将AddDataToCarsModel迁移更改为:

class AddDataToCarsModel < ActiveRecord::Migration[5.0]

  class Car < ActiveRecord::Base
    self.table_name = 'cars'
  end

  def change
    # some cars are missing their created timestamp
    Car.where(created_at: nil).each do |car|
      date = Time.zone.now
      car.update_attribute(:created_at, date)
    end
  end
end

因此,您Cars只能在此迁移中使用模型。这不会影响您的应用程序生命周期。


推荐阅读