【问题标题】:Paperclip add image from URL in has_many association回形针在 has_many 关联中从 URL 添加图像
【发布时间】:2016-02-25 00:03:10
【问题描述】:
【问题讨论】:
标签:
ruby-on-rails
ruby
ruby-on-rails-4
paperclip
has-many
【解决方案1】:
这是一个很好的要点(我没有写)。它应该能让你到达那里: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
感谢作者。
以后,通常最好在发布代码时尝试解决问题。