Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jgv
Forked from trevorturk/gist:34895
Created December 20, 2011 19:03
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jgv/1502777 to your computer and use it in GitHub Desktop.
Save jgv/1502777 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
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))
self.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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment