2016-02-28 32 views
0

我在我的rails應用程序中使用回形針進行配置文件圖片上傳功能。這對於將圖像上傳到配置文件的默認情況非常適用,但我希望允許沒有圖片的用戶從一個預選的「庫存」圖像中選擇一個。在回形針中存儲一個基於URL的圖像

這些圖像在我的資產圖像文件夾中本地託管。因此,在這些場合下,我希望能夠將圖像添加到EventImage對象,而無需實際上傳圖像,而只需在本地路徑中引用URL即可。

我已經嘗試了幾乎每個來自這個職位的答案:Save image from URL by paperclip但他們都沒有工作。我使用回形針版本paperclip (4.3.1 37589f9)

當我嘗試的解決方案:

def photo_from_url(url) 
    puts "we got:"+url 
    Thread.new do 
    self.photo = URI.parse(url) 
    end 
    end 

則導致無圖像參考存儲,也不管URL的一個形象我傳遞進方法,它永遠不會顯示當我這樣做時,我的圖像:<%= image_tag @event.event_images.first.photo.url %> - 相反,它顯示圖像未找到或存儲時的默認圖像。

我也必須把它放在一個新的線程,否則它會被捆綁和阻塞/導致超時這似乎是一個URI.parse問題,也是圖像最終失敗驗證,因爲照片是'空'這在我的驗證中是不允許的,所以我最終刪除了驗證存在行:照片,但仍不能解決問題。我真的只想要模型回形針方法:照片 - 有時指向一個本地URL,而我其他時間正確地上傳文件。

看到整個班級這裏:

# == Schema Information 
# 
# Table name: event_images 
# 
# id     :integer   not null, primary key 
# caption   :string 
# event_id   :integer 
# created_at   :datetime   not null 
# updated_at   :datetime   not null 
# photo_file_name :string 
# photo_content_type :string 
# photo_file_size :integer 
# photo_updated_at :datetime 
# 

class EventImage < ActiveRecord::Base 
    attr_accessor :PAPERCLIP_STORAGE_OPTS 

    has_attached_file :photo , PAPERCLIP_STORAGE_OPTS 

    validates_attachment_presence :photo 
    validates_attachment_content_type :photo, :content_type => ["image/jpg", "image/jpeg", "image/gif", "image/png"] 
    validates_with AttachmentSizeValidator, :attributes => :photo, :less_than => 3.megabytes 

    belongs_to :event 

    def photo_from_url(url) 
    Thread.new do 
    self.photo = URI.parse(url) 
    end 
    end 
end 

回答

0

相反,我已經決定,這將是最好的「canned_image_id」添加到EventImage模型,然後在其中可以選擇的型號使用PHOTO_URL方法根據圖像是否爲固定圖像返回回形針url或固定圖像url。它也隱藏了一個輔助方法的複雜性:)