開発環境
Rails: 5.2.1
Ruby: 2.5.0
実装
Modelの例として下記のようなuserのModelがあったとする。
user.rb
class User < ApplicationRecord
# ファイルをダウンロードするために必要なライブラリ
require 'open-uri'
has_one_attached :icon
end
画像をダウンロードして、userに紐づける方法はこうだ。
# 画像url
imageUrl = "..."
# 画像のファイルオブジェクト
imageFile = open(imageUrl)
# userに画像を紐づける
user.icon.attach(io: imageFile, filename: "filename", content_type: 'image/jpg')