Duplicate rails object with associations and paper clips attachments

I have an object with several associations. Some of these related objects have folders attached to the folder that are stored on S3. If I duplicate an object and associations, it works fine, but the attachments are not duplicated.

This works without getting images:

copy_salon = @salon.dup 
copy_salon.about_us_versions = @salon.about_us_versions.collect{|about_us| about_us.dup}

I tried to get a link to the image as follows:

copy_salon = @salon.dup 
copy_salon.about_us_versions = @salon.about_us_versions.collect{|about_us| 
                                                                  about_us_dup = about_us.dup
                                                                  if about_us.about_us_image then about_us_dup.about_us_image = about_us.about_us_image end
                                                                  if about_us.team_image then about_us_dup.team_image = about_us.team_image end
                                                                  about_us_dup
                                                                }

But then I get the error "cannot convert nil to String", possibly because not all images are installed.

+2
source share
2 answers

, , . , dup . ?

copy_salon = @salon.dup 
copy_salon.about_us_versions = @salon.about_us_versions.collect{|about_us| 
                                                                  about_us_dup = about_us.dup
                                                                  unless about_us.about_us_image.url == "/about_us_images/original/missing.png" then about_us_dup.about_us_image = about_us.about_us_image end
                                                                  unless about_us.team_image.url == "/team_images/original/missing.png" then about_us_dup.team_image = about_us.team_image end
                                                                  about_us_dup
                                                                }
+1

, dup, , Paperclip:

def dup
  duplicate = super

  # attachment_definitions is defined if model has paperclip attachments
  return duplicate unless self.class.respond_to?(:attachment_definitions)

  duplicate.tap do |d|
    self.class.attachment_definitions.keys.each do |name|
      d.send("#{name}=", send(name)) if send(name).exists?
    end
  end
end

: ApplicationRecord, .

+1

Source: https://habr.com/ru/post/1539317/


All Articles