开发者

Paperclip fetch image directly via url

开发者 https://www.devze.com 2023-02-07 02:06 出处:网络
It\'s it possible to fetch an image via url using PaperClip ? It\'s possible with fleximage, but fleximage has no support for Rails3 so I\'ve switched over to paperclip.

It's it possible to fetch an image via url using PaperClip ? It's possible with fleximage, but fleximage has no support for Rails3 so I've switched over to paperclip.

At present, I'm fetching the image via curl, saving it on the hdd and load it via image_file of paperclip.开发者_运维知识库

I've found no real solution via google, so hopefully you can help me.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号