Image uploading from a URL

Right now my site can only upload images from my computer, but I want to make it upload from URL instead.  So that’s what I’m going to be doing now. 🙂

If I load the schema file in the db folder, I can see that right now I’m storing the following information about my pins:

create_table "pins", :force => true do |t|
t.string "description"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "user_id"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"

If I want to add image URL in there, I first need to create a migration by doing:

$ rails generate migration AddImageRemoteUrlToPins image_remote_url:string

Now I need to run rake db:migrate to make the database changes.

Now we need to edit the model to tell it what to do if a user wants to upload an image from a remote URL.  I need to  edit the pin.rb model file and make the image_remote_url accessible by adding the following to attr_accessible:

attr_accessible :description, :image, :image_remote_url

Also apparently something with Ruby is that once I define an attribute I can dig into it deeper.  At the bottom of the pin.rb file I add:

	def image_remote_url=(url_value)
 		self.image = URI.parse(url_value) unless url_value.blank?

So that was some confusing stuff right there.  Apparently in this case, super means that it’s going to fall back on whatever functionality was in the original method.  self in self.image refers to the pin.

Next we need to edit the _form.erb file so that it’s added to our views so people can try to paste in a URL.  I add this to the file:

<%= f.input :image_remote_url, label: "or enter a URL" %>

Bam, done.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s