回形针动态url?

Paperclip dynamic url?

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

如果 instance Product.image_file_name 包含 "old:" 我希望 URL 类似于 cloudfront_url/products/file_name,如果不包含 - 它应该使用新的 S3 bucket/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。

如果我按照 中所述将其包装在 lambda 中,我会得到 Error "no implicit conversion of Proc into String"

你们成功让 Paperclip 与动态 URL 一起工作了吗?如果你知道怎么做,那将是你的救命恩人。

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

解决方案是在您的架构中引入一个名为 image_url 的新列。 该列将在 initialize/update 上在 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