我有一个现有的模型,它使用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"发布于 2019-02-08 06:23:18
问题是这个文件实际上并不存在于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
endhttps://stackoverflow.com/questions/54582355
复制相似问题