2012-07-11 63 views
2

我有一个有多个关联的对象。其中一些关联对象在S3中存储了回形针附件。如果我复制对象和关联它工作正常,但附件不重复。用关联和回形针附件复制一个rails对象

这这里工作没有得到的图像:

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

我试图让这样的图像链接:

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 
                   } 

但后来我收到错误“不能转换成零字符串',可能是因为没有设置所有图像。

回答

1

明白了,并不优雅,但工作。我曾希望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

是的,我认为'Paperclip :: Attachment'目前不知道如何自我复制。你介意卷起袖子并修补它吗?这绝对有一些功能,我将它合并:) – sikachu 2012-07-12 00:42:17

+0

很想在那里帮忙,也许在几个星期内。刚开始使用rails,来自Google的... – 2012-07-17 23:27:08

1

我把它简单的通过覆盖dup,至少回形针附件:

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所以从它的每一个模型的好处来定义。