Skip to content

Instantly share code, notes, and snippets.

@trevorturk
Created December 11, 2008 21:56
Show Gist options
  • Save trevorturk/34895 to your computer and use it in GitHub Desktop.
Save trevorturk/34895 to your computer and use it in GitHub Desktop.
Allow "uploads via url" with Rails and Paperclip
#
# See also: http://almosteffortless.com/2008/12/11/easy-upload-via-url-with-paperclip/
#
# Allow "uploads via url" with Rails and Paperclip
#
# http://www.thoughtbot.com/projects/paperclip
# http://github.com/thoughtbot/paperclip/tree/master
# http://groups.google.com/group/paperclip-plugin/browse_thread/thread/456401eb93135095
#
# This example is designed to work with a "Photo" model that has an "Image" attachment
# It requires adding a <?>_remote_url column for your attachment - "image_remote_url" in this case
#
# app/controllers/photos_controller.rb
class PhotosController < ApplicationController
def create
@photo = Photo.new(params[:photo])
if @photo.save
redirect_to photos_path
else
render :action => 'new'
end
end
end
# app/views/photos/new.html.erb
<%= error_messages_for :photo %>
<% form_for :photo, :html => { :multipart => true } do |f| %>
Upload a photo: <%= f.file_field :image %><br>
...or provide a URL: <%= f.text_field :image_url %><br>
<%= f.submit 'Submit' %>
<% end %>
# app/models/photo.rb
require 'open-uri'
class Photo < ActiveRecord::Base
attr_accessor :image_url
has_attached_file :image # etc...
before_validation :download_remote_image, :if => :image_url_provided?
validates_presence_of :image_remote_url, :if => :image_url_provided?, :message => 'is invalid or inaccessible'
private
def image_url_provided?
!self.image_url.blank?
end
def download_remote_image
io = open(URI.parse(image_url))
io.original_filename = io.base_uri.path.split('/').last
self.image = io
self.image_remote_url = image_url
rescue # catch url errors with validations instead of exceptions (Errno::ENOENT, OpenURI::HTTPError, etc...)
end
end
@pelargir
Copy link

pelargir commented May 1, 2013

This results in a stack overflow in the latest version of Paperclip (v3.4.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment