如何迁移Carrierwave文件列在Rails的另一个模型

问题描述 投票:0回答:1

我有一个现有的模式存储使用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个回答
0
投票

问题是,该文件确实没有对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
© www.soinside.com 2019 - 2024. All rights reserved.