I have a Job model which can have many attachments. The Attachment model has a CarrierWave uploader mounted on it.
class Job < ActiveRecord::Base
has_many :attachments
end
class Attachment < ActiveRecord::Base
mount_uploader :url, AttachmentUploader
belongs_to :job
end
Jobs can be cloned and cloning a job should create new Job and Attachment records. This part is simple.
The system then needs to copy the physical files to the upload location associated with the cloned job.
Is there a simple way to do this with CarrierWave? The solution should support both the local filesystem and AWS S3.
class ClonedJob
def self.create_from(orig_job)
@job_clone = orig_job.dup
if orig_job.attachments.any?
orig_job.attachments.each do |attach|
cloned_attactment = attach.dup
# Need to physically copy files at this point. Otherwise
# this cloned_attachment will still point to the same file
# as the original attachment.
@job_clone.attachments << cloned_attachment
end
end
end
end
I’ve pasted below the module I whacked together to accomplish this. It works but there is still a couple of things I would improve if it mattered enough. I just left my thoughts inline in the code.
I use it like this: