【问题标题】:Paperclip dynamic url?回形针动态网址?
【发布时间】:2015-07-15 21:26:35
【问题描述】:

我有一个带有 Paperclip image attachment 列的 Rails ActiveModel 产品,需要从 2 个来源获取它的 image.url。一个是旧的 S3 存储桶/CloudFront,另一个是我们的新 S3 存储桶/CloudFront。他们拥有完全不同的凭据。

如果 instance Product.image_file_name 包含“旧:”,我希望 URL 类似于 cloudfront_url/products/file_name,如果不是 - 它应该使用新的 S3 存储桶/CloudFront。上传只会在新的 S3 存储桶上进行,但如果image_file_name 包含old:,它将回退到旧的存储桶上。

目前我只获得了新 S3 存储桶的授权,而不是旧存储桶。

我已经读到我应该这样做:

    class Product
      has_attached_file: :image, url: dynamic_url_method

      def dynamic_url_method
         .... do some logic based on image_file_name
         return constructed_url
      end
    end

但是,当我这样做时,我得到未定义的局部变量 dynamic_url_method。

如果我按照https://stackoverflow.com/a/10493048 中的说明将其包装在 lambda 中,我会得到 Error "no implicit conversion of Proc into String"

你们成功让 Paperclip 使用动态 URL 了吗?如果您知道如何操作,这将是一个救命稻草。

【问题讨论】:

  • 应该是一个符号:has_attached_file: :image, url: :dynamic_url_method,你漏掉了冒号。稍微担心的是 lambda 应该可以工作。你能粘贴你得到的错误的堆栈跟踪吗?

标签: ruby-on-rails amazon-web-services amazon-s3 paperclip


【解决方案1】:

完全放弃为回形针附件提供动态 URL 参数的整个想法。它破坏了 S3 图像上传,导致 Paperclip 无法确定使用哪个 URL。

解决方案是在您的架构中引入一个名为image_url 的新列。 该列将在 ActiveModel 中的初始化/更新时更新并在网页中使用。

在代码中

class Product
  has_attached_file: :image
  after_create :update_image_url
  after_update :update_image_url

  def update_image_url
     new_image_url =  # some logic based on image_file_name that would either return the CloudFront URL or save the URL from image.url which is generated by Paperclip
     # Paperclip does not update image_file_name_changed? so we can't say
     # after_create or after_update if: image_file_name_changed? instead  
     # we have to manually check that image_url and new_image_url are different
     update(image_url: new_image_url) if image_url != new_image_url
  end
end

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2012-07-20
    相关资源
    最近更新 更多