【问题标题】:How to attach image from the url in Rails Active Storage如何从 Rails Active Storage 中的 url 附加图像
【发布时间】:2026-02-17 22:25:01
【问题描述】:

我想将图像附加到 rake 任务中的记录。我唯一的图像是 URL。这是图片的 URL https://cdn.iconscout.com/icon/free/png-256/google-analytics-7-722699.png

我在 * answer 中使用了这种方法。

require 'open-uri'
downloaded_file = open(tool.image)
new_tool.image.attach(io: downloaded_file, filename: "foo.png")

这会产生以下错误。

ActiveStorage::IntegrityError: Unsupported source URL: #<StringIO:0x00007f9bd9759f28>
Caused by:
CloudinaryException: Unsupported source URL: #<StringIO:0x00007f9bd9759f28>

有人可以帮我吗?

【问题讨论】:

    标签: ruby-on-rails cloudinary rails-activestorage


    【解决方案1】:

    在这种情况下,我认为您应该将包含图像 URL 的字符串传递给open

    require 'open-uri'
    
    image_url = "https://cdn.iconscout.com/icon/free/png-256/google-analytics-7-722699.png"    
    downloaded_file = open(image_url)
    
    new_tool.image.attach(io: downloaded_file, filename: "foo.png")
    

    【讨论】:

    • 感谢您的回复。在我的问题中,tool.image 是图像的 URL。
    • @SalmanHaseebSheikh 您使用的是什么版本的 Ruby 和 Rails?
    • Ruby 2.7.0 和 Rails 6.0.2。
    • 你确定tool.image返回一个字符串吗?你能把tool.image.class的输出放在这里吗?
    • 最新版本的 ruby​​ 建议使用 URI.open 代替:警告:不推荐通过 Kernel#open 调用 URI.open,直接调用 URI.open 或使用 URI#open