【问题标题】:Storing an image based upon nothing but a URL in Paperclip仅基于 Paperclip 中的 URL 存储图像
【发布时间】:2016-06-11 16:26:15
【问题描述】:

我在我的 rails 应用程序中使用回形针来上传个人资料图片。这适用于将图片上传到个人资料的默认情况,但我希望允许没有图片的用户从一组预先设定的“库存”图片中进行选择。

这些图像托管在本地,位于我的资产图像文件夹中。因此,在这些情况下,我希望能够在不实际上传图像的情况下将图像添加到我的 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 的问题,而且图像最终验证失败,因为照片是“空的”在我的验证中是不允许的,所以我最终删除了 :photo 上的验证存在行,这仍然不能解决问题。我真的只是希望模型回形针方法 :photo - 有时指向本地 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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 rubygems paperclip


    【解决方案1】:

    相反,我决定最好将“canned_image_id”添加到 EventImage 模型中,然后在模型中使用 photo_url 方法,该方法可以选择返回回形针 url 或罐头图像 url,具体取决于是否不是图像是罐头图像。它还将这种复杂性隐藏在辅助方法后面:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      • 2016-07-31
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-19
      相关资源
      最近更新 更多