如何使用 Carrierwave 下载和存储远程图像 URL

How to Download and Store Remote Image URLs with Carrierwave

抱歉,如果这个问题有明显的答案,我对 rails 有点生疏。

一些背景:我正在构建一个 Rails API,它应该抓取食谱,存储它们,并将它们提供给我的前端 Ember 应用程序。到目前为止,一切似乎都很好,除了我一直卡在图像上。由于这些图像非常大,我想下载图像并处理它们,然后将它们上传到 S3。为了实现这一点,我认为 carrierwave 可能会成功,但我似乎无法为其提供远程 URL。这是我目前所在的位置:

#image.rb
class Image < ActiveRecord::Base
mount_uploader :photos, PhotoUploader

belongs_to :imageable, polymorphic: true
end

#recipe.rb
class Recipe < ActiveRecord::Base
belongs_to :blog
has_many :images, as: :imageable
has_and_belongs_to_many :ingredients
end

class PhotoUploader < CarrierWave::Uploader::Base
...

在我的 rails 控制台中,我可以执行

之类的操作

Recipe.first.images => []

但是我无法使用图像 URL 从我的控制台填充图像数组。如何提供载波远程图像 URL 并将它们存储在 S3 上?

您可以通过将值传递到远程字段名称来实现。

在您的示例中,它将是 remote_photos_url

因此,当您制作新图像时,代码将如下所示:

Image.new remote_photos_url: 'http://www.domain.com/path-to-image', recipe_id: n

Here is a link to the docs

然后只要您的 S3 设置好并且 CarrierWave 上传设置好,它就会按照您想要的方式运行。