How to save an image from a url with rails active storage?

后端 未结 3 1773
野的像风
野的像风 2020-12-29 07:46

I\'m looking to save a file (in this case an image) located on another http web server using rails 5.2 active storage.

I have an object with a string parameter for s

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-29 08:23

    Just found the answer to my own question. My first instinct was pretty close...

    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
    

提交回复
热议问题