【问题标题】:How to migrate a Carrierwave file to a column in another model in Rails如何将 Carrierwave 文件迁移到 Rails 中另一个模型的列
【发布时间】:2019-02-07 21:11:46
【问题描述】:

我有一个使用 Carrierwave 存储文件的现有模型。我想将该文件移至新模型,但我似乎无法正确读取该文件

这是我现有的模型:

class ShipmentNote < ActiveRecord::Base
  has_many :shipment_note_files # this is actually the new model I want to move the files to
  mount_uploader :file, DocumentUploader
  ....
end

还有我的新模型:

class ShipmentNoteFile < ActiveRecord::Base
  belongs_to :shipment_note
  mount_uploader :file, DocumentUploader
end

这是我认为可行的:

ShipmentNote.where.not(file: nil).each do |shipment_note|
  # create a new file in the shipment_note_files
  shipment_note.shipment_note_files.create(file: shipment_note.file)
  # remove from shipment_note
  shipment_note.remove_file!
  shipment_note.save
end

但它抛出以下错误,暗示文件字段为空:

PG::NotNullViolation: ERROR:  null value in column "file" violates not-null constraint
DETAIL:  Failing row contains (15, null, 46689, 2019-02-07 20:56:54.503714, 2019-02-07 20:56:54.503714, null).
: INSERT INTO "shipment_note_files" ("file", "shipment_note_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"

【问题讨论】:

    标签: ruby-on-rails-4 carrierwave data-migration


    【解决方案1】:

    问题是该文件在 S3 上确实不存在。我不得不挽救错误并且一切正常:

    ShipmentNote.where.not(file: nil).each do |shipment_note|
      begin
        # create a new file in the shipment_note_files
        shipment_note.shipment_note_files.create(file: shipment_note.file)
        # remove from shipment_note
        shipment_note.remove_file!
        shipment_note.save
      rescue => exception
        p "file not exist: #{shipment_note.id}"
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-22
      • 2011-09-02
      • 1970-01-01
      • 2010-12-23
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      • 2011-12-14
      相关资源
      最近更新 更多