【问题标题】:Paperclip add image from URL in has_many association回形针在 has_many 关联中从 URL 添加图像
【发布时间】:2016-02-25 00:03:10
【问题描述】:

我有这个模型: 产品 -> Products_Images。

我可以从上传图像的表单添加多个图像,这是我的计算机。我想从 URL 添加图片而不是本地图片。

Paperclip 已添加此功能: https://github.com/thoughtbot/paperclip/wiki/Attachment-downloaded-from-a-URL 但我不知道如何在 has_many 关联中应用它。

我尝试在 ProductImages 模型中添加一个方法,并在创建产品后为每个 URL 调用它。不知道是不是一定要直接在Product模型中使用这个方法。

回形针wiki的方法应该放在哪里?

【问题讨论】:

    标签: 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
    

    感谢作者。

    以后,通常最好在发布代码时尝试解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 2013-07-16
      相关资源
      最近更新 更多