ruby-on-rails - 修复已删除表(包括模型)的现有迁移的未初始化常量错误
问题描述
我有一个一年前创建的汽车表,现在需要重命名为汽车表。
车表迁移
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
错误,因为我已经删除了作为其中一部分的汽车模型。这些情况的最佳做法是什么?是否值得运行一年前创建的旧迁移并对其进行更新?我们该如何处理这些情况?
谢谢您的帮助。
解决方案
作为迁移的修复,您可以将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
只能在此迁移中使用模型。这不会影响您的应用程序生命周期。
推荐阅读
- c# - C# 程序不会在其他计算机上启动。OleDB 命令中的错误
- user-interface - 如何使用 svg 文件而不是直接在 Markdown 中使用 svg 元素从模板中绘制 MDC 复选框刻度线
- c - 在 for 循环的下一次迭代开始后,指针指向的数据在复制另一个列表末尾的列表时被破坏
- javascript - 从 AJAX 请求调用 django 视图(解析 celery task_id)
- android - 如何在打盹模式下检测维护窗口将关闭事件?
- selenium - Xvfb 的 Jenkins 流水线“包装”阶段开始
- reactjs - 反应 setState 无法正常工作
- java - Ignite Spring Data 是否支持 Spring Boot 2?
- java - 为 Libftd3xx 编写 JNA 包装器
- angular - 如何防止只从 mat-datepicker 中选择 DAY?