Question

I have an app which you can store order/invoices in. I'm building a simple feature where you can duplicate invoices for my customers. I wrote this method in my Order.rb model which:

Takes the invoice, duplicates the associated lineitems, adds the new OrderID into them...and does the same for associated images.

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

Unfortunately, you can't just .dup the image because there's all this associate expiration stuff since I'm storing images on S3. Is there a way to regenerate the image maybe using its image_url?

The error I get when running this is below. Which tells me not all the associated image information is dup'd correctly.

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, 
Was it helpful?

Solution 2

This is actually how I did it for each lineitem on an order:

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

OTHER TIPS

i think you can do the following

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

It is a bit late however this is my solution. I have had far too many problems with .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

Here is my upload.rb

class Upload < ActiveRecord::Base
  belongs_to :uploadable, polymorphic: true
  mount_uploader :filename, ImageUploader
end

Hope it helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top