如何使用rails active storage从url保存图像?

我正在寻找使用rails 5.2活动存储保存位于另一个http Web服务器上的文件(在本例中为图像)。

我有一个带有源URL的字符串参数的对象。 然后在before_save上我想抓取远程图像并保存。

示例:图像的URL http://www.example.com/image.jpg 。

require 'open-uri' class User < ApplicationRecord has_one_attached :avatar before_save :grab_image def grab_image #this indicates what I want to do but doesn't work downloaded_image = open("http://www.example.com/image.jpg") self.avatar.attach(downloaded_image) end end 

在此先感谢您的任何建议。

刚刚找到了我自己的问题的答案。 我的第一直觉非常接近……

 require 'open-uri' class User < ApplicationRecord has_one_attached :avatar before_save :grab_image def grab_image downloaded_image = open("http://www.example.com/image.jpg") self.avatar.attach(io: downloaded_image , filename: "foo.jpg") end end