Paperclip fetch image directly via url

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 13:11:15

Yes this is possible and amazingly simple.

In your model:

#we use this to get the image.
require 'rest-open-uri'
Class Model << ActiveRecord::Base
has_attached_file :picture

#Get the picture from a given url.
def picture_from_url(url)
    self.picture = open(url)
end

And then you can do something like this:

#controller
@model.picture_from_url(<Your URL here>)

And because we saved the image with the rest of the object. You can just use this in your views:

<%= image_tag @model.picture.url %>

Hope this helps!

Does the <modelname>.<attachmentname>.url method not do what you're looking for?

In other words, if your model is called Foo, and you set it to has_attached_file :bar then foo.bar.url should give the url of your image, which you can put into an image_tag or a link_to or whatever you want.

Could you clarify what you mean if that isn't what you're looking for?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!