0

I am using paperclip for a profile picture upload feature in my rails app. This works nicely for the default case of uploading images to a profile, but I want to allow users without a picture to pick from one of a selection of precanned 'stock' images.

These images are hosted locally, within my assets images folder. Therefore on these occasions I want to be able to add an image to my EventImage object without actually uploading an image, more just referencing a URL at a local path.

I have tried pretty much every answer from this post : Save image from URL by paperclip but none of them seem to work. I am using paperclip version paperclip (4.3.1 37589f9)

When I try the solution of :

def photo_from_url(url)
    puts "we got:"+url
    Thread.new do
    self.photo = URI.parse(url)
    end
  end

It results in no image reference being stored, and regardless of the URL to an image I pass into that method, it never displays my image when I do : <%= image_tag @event.event_images.first.photo.url %> - instead it shows the default image for when an image has not been located or stored.

I also have to put it in a new thread otherwise it gets tied up and blocks / resulting in a timeout which seems to be a problem with URI.parse, also the image ends up failing validation as photo is 'empty' which is not allowed in my validation, so I end up removing the validation presence line on :photo, which still does not solve the problem. I really just want the models paperclip method :photo - to point to a local url sometimes, and my correctly normally uploaded files other times.

See the whole class here:

# == Schema Information
#
# Table name: event_images
#
#  id                 :integer          not null, primary key
#  caption            :string
#  event_id           :integer
#  created_at         :datetime         not null
#  updated_at         :datetime         not null
#  photo_file_name    :string
#  photo_content_type :string
#  photo_file_size    :integer
#  photo_updated_at   :datetime
#

class EventImage < ActiveRecord::Base
  attr_accessor :PAPERCLIP_STORAGE_OPTS

  has_attached_file :photo , PAPERCLIP_STORAGE_OPTS

  validates_attachment_presence :photo
  validates_attachment_content_type :photo, :content_type => ["image/jpg", "image/jpeg", "image/gif", "image/png"]
  validates_with AttachmentSizeValidator, :attributes => :photo, :less_than => 3.megabytes

  belongs_to :event

  def photo_from_url(url)
    Thread.new do
    self.photo = URI.parse(url)
    end
  end
end
Community
  • 1
  • 1
RenegadeAndy
  • 5,440
  • 18
  • 70
  • 130

1 Answers1

0

Instead, I have decided that it would be best to add a 'canned_image_id' to the EventImage model, then use a photo_url method in the model which can choose to return either the paperclip url or the canned image url depending on whether or not the image is a canned image. It also hides this complexity behind a helper method :)

RenegadeAndy
  • 5,440
  • 18
  • 70
  • 130