LoginSignup
1
1

More than 5 years have passed since last update.

【Rails】ダウンロードした画像をActiveStorageのModelに紐づける方法

Posted at

開発環境

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')
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1