0
votes

In a form designated for a desktop image attachment, enter image description here I want to instead attach a file in the form from a URL(without adding a new field, want to attach using the attachment form above). Is this first and foremost possible within Rails? Here's where I'm at so far.


Currently, I'm using Paperclip for image attachments and am able to get a file by using:

image_url = URI.parse('http://www.flicker/image.png')

imageFile = open(URI.parse(image_url))

And if you were to call the imageFile it would output this: #< File : 0x007fad310ca238>

I've setup everything in my model:
has_attached_file :image, :styles => { :medium => "300x300#", :thumb => "100x100#" }
validates_attachment_content_type :image, :content_type => /\Aimage/

Controller:

 @deal = current_user.deals.build(
     #fills out other fields as well but deleted them
     #attatch image to field
    image: imageFile
    )

But unfortunately simply assigning in the new action for the image: to be an imageFile doesn't work. Any help?

1

1 Answers

0
votes

I might be misunderstanding what you need, but the easiest way is to remove the file field from your form and instead use an attr_reader for a new field which is the URL of the image. Then in your model, make your URI.parse call for the value in that field and then return that.

So your deal model would look something like

class Deal < ActiveRecord::Base
  attr_reader :image_remote_url
  has_attached_file :image, :styles => { :medium => "300x300#", :thumb => "100x100#" } 
  validates_attachment_content_type :image, :content_type => /\Aimage/

  def image_remote_url=(url)
    self.image = URI.parse(url)
    @image_remote_url = url
  end
end

This way you can allow either option, url or file upload.