2016-02-28 34 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。它也隐藏了一个辅助方法的复杂性:)