我有一个应用程序,您可以存储订单/发票。我正在构建一个简单的功能,您可以为我的客户复制发票。我在Order.rb模型中编写了这个方法:
获取发票,复制相关的lineitems,将新的OrderID添加到其中......并对相关图像执行相同操作。
def self.duplicate_it(invoice)
new_invoice = invoice.dup
new_invoice.save
invoice.lineitems.each do |l|
new_lineitem = l.dup
new_lineitem.order_id = new_invoice.id
new_lineitem.save
end
invoice.images.each do |i|
new_image = i.dup
new_image.order_id = new_invoice.id
new_image.save
end
return new_invoice
end
不幸的是,你不能只是.dup
图像,因为我在S3上存储图像,因此存在所有这些关联到期的东西。有没有办法使用image_url重新生成图像?
运行时遇到的错误如下。这告诉我并非所有相关的图像信息都被正确复制。
Showing /Users/bruceackerman/Dropbox/printavo/app/views/orders/_image-display.erb where line #3 raised:
undefined method `content_type' for nil:NilClass
Extracted source (around line #3):
1: <% @order.images.each do |image| %>
2: <% if image.image && image.image.file %>
3: <% if image.image.file.content_type == "application/pdf" %>
4: <%= link_to image_tag("/images/app/pdf.jpg",
5: :class => 'invoice-image'),
6: image.image_url,
答案 0 :(得分:0)
我认为您可以执行以下操作
invoice.images.each do |i|
new_image = new_invoice.images.new({ order_id: new_invoice.id })
new_image.image.download!(i.image_url)
new_image.store_image!
new_image.save!
end
答案 1 :(得分:0)
这实际上是我为订单上的每个lineitem做的:
def self.duplicate_it(invoice)
new_invoice = invoice.dup :include => {:lineitems => :images} do |original, kopy|
kopy.image = original.image if kopy.is_a?(Image)
end
new_invoice.save!
return new_invoice
end
答案 2 :(得分:0)
这有点晚了但是这是我的解决方案。 .download!
if @record.duplicable?
new_record = @record.dup
if new_record.save
@record.uploads.each do |upload|
new_image = new_record.uploads.new({ uploadable_id: new_record.id })
new_image.filename = Rails.root.join('public'+upload.filename_url).open
new_image.save!
end
end
这是我的upload.rb
class Upload < ActiveRecord::Base
belongs_to :uploadable, polymorphic: true
mount_uploader :filename, ImageUploader
end
希望它有所帮助!