2016-02-25 25 views
0

我有這種模型: 產品 - >產品_Images。回形針添加圖像從URL has_many協會

我可以從表單上添加圖像的多個圖像,它是我的電腦。我想從網址添加圖片而不是本地圖片。

回形針已添加此功能: https://github.com/thoughtbot/paperclip/wiki/Attachment-downloaded-from-a-URL 但我不知道如何將其應用於has_many關聯。

我試過在ProductImages模型中添加一個方法,並在創建產品後爲每個URL調用它。我不知道是否必須直接在產品模型中使用此方法。

我應該在哪裏嘗試將Paperclip的wiki的方法?

回答

0

這是一個偉大的主旨(我沒寫)。它應該讓你在那裏:https://gist.github.com/jgv/1502777

require 'open-uri' 

class Photo < ActiveRecord::Base 

    has_attached_file :image # etc... 

    before_validation :download_remote_image, :if => :image_url_provided? 

    validates_presence_of :image_remote_url, :if => :image_url_provided?, :message => 'is invalid or inaccessible' 

    private 

    def image_url_provided? 
    !self.image_url.blank? 
    end 

    def download_remote_image 
    io = open(URI.parse(image_url)) 
    self.original_filename = io.base_uri.path.split('/').last 
    self.image = io 
    self.image_remote_url = image_url 
    rescue # catch url errors with validations instead of exceptions (Errno::ENOENT, OpenURI::HTTPError, etc...) 
    end 

end 

所有功勞歸於作者。

將來,通常最好是在解決問題的時候發佈代碼。