首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Rails中将Carrierwave文件迁移到另一个模型中的列

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

Stack Overflow用户
提问于 2019-02-08 05:11:46
回答 1查看 361关注 0票数 0

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

这是我现有的模型:

代码语言:javascript
运行
复制
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

我的新模型:

代码语言:javascript
运行
复制
class ShipmentNoteFile < ActiveRecord::Base
  belongs_to :shipment_note
  mount_uploader :file, DocumentUploader
end

这是我认为可行的方法:

代码语言:javascript
运行
复制
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

但它抛出了以下错误,这意味着文件字段为空:

代码语言:javascript
运行
复制
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"
EN

回答 1

Stack Overflow用户

发布于 2019-02-08 06:23:18

问题是这个文件实际上并不存在于S3上。我不得不修复这个错误,一切都运行得很好:

代码语言:javascript
运行
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54582355

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档