Uploading Images from URLs in Rails ActiveStorage

This article will discuss how to attach images to a model from URLs with ActiveStorage.

In the application root, run these commands:

1
2
rails active_storage:install
rails db:migrate

Then in your model, put post.rb and make sure you have an image attached.

1
2
3
class Post < ApplicationRecord
 has_one_attached :image
end

For uploading images from the web, open-uri is required. Go ahead and test your implementation from the console.

1
2
3
4
5
6
7
8
9
rails console
require 'open-uri'
image = open('https://cdn3.iconfinder.com/data/icons/flat-icons-web/40/Skype-512.png')
post = Post.first

post.image.attach(io: image, filename: "image-from-the-web")

post.image.attached?
=> true 

In this way, images from the web can be easily uploaded, whether from the console or by using rake tasks. Happy uploading!