即使未使用,运行迁移也会导致找不到类

时间:2014-12-20 14:44:57

标签: ruby-on-rails ruby-on-rails-4

我正在尝试运行迁移文件,但是当它运行时我会得到一个

undefined class/module BookingLib::/......./db/migrate/20141216090123_migrate_old_advanced_price_data.rb:18:in `block in up'

迁移文件:

def up
    add_column :advanced_prices, :seller_id, :integer
    add_column :advanced_prices, :buyer_id, :integer
    add_column :advanced_prices, :seller_type, :string
    add_column :advanced_prices, :buyer_type, :string

    Shipment.all.each do |shipment|
      advanced_price             = shipment.advanced_price

      next unless advanced_price
      advanced_price.seller_id   = shipment.carrier_product.company_id
      advanced_price.seller_type = Company.to_s
      advanced_price.buyer_id    = shipment.customer.id
      advanced_price.buyer_type  = Customer.to_s

      shipment.advanced_prices << advanced_price
      shipment.save! <====================================== Failing line 
    end

    remove_column :advanced_prices, :customer_id, :integer
    remove_column :advanced_prices, :company_id, :integer

  end

配送费:

  class Shipment < ActiveRecord::Base
  .........
  serialize :package_dimensions, PackageDimensions
  serialize :shipment_errors, Array
  serialize :shipment_warnings, Array

  validates :shipping_date,      presence: true
  validates :number_of_packages, presence: true, numericality: { only_integer: true, greater_than: 0 }
  validates :package_dimensions, presence: true
  validates :dutiable,           inclusion: { in: [true, false] }
  validates :carrier_product,    presence: true
...

即使保存记录的模型与该类无关。任何人都知道为什么会这样?

2 个答案:

答案 0 :(得分:2)

这结果是一个序列化问题。

当反序列化PackageDimensions时,它反过来加载在类BookingLib中定义的错误类。在开发中,Rails使用自动加载延迟加载类,但由于错误未在其自己的文件中定义,因此自动加载无法解决错误常量。

解决方案是在ShipmentPackageDimensions中包含要求:

require 'booking_lib'

这将确保在反序列化发生之前加载BookingLib类,以及因此在其中声明的错误。

答案 1 :(得分:0)

您还需要执行&#39; Shipment.reset_column_information&#39;在Shipment.all.each之前发货|&#39;。这可确保从数据库加载所有Shipment数据,并且不使用缓存数据。

http://apidock.com/rails/ActiveRecord/ModelSchema/ClassMethods/reset_column_information

这可能无法解决您的问题,但我没有足够的意见来评论这个问题。