Image Upload and Thumbnails

Created by Myriam Leggieri, @iammyr for Rails Girls Galway The basic guides that have been merged and adapted are the Ruby on Rails Tutorial, the basic RailsGirls app and the tutorials for creating thumbnails, authenticating users, adding design, deploying to OpenShift and adding comments.

We need to install a piece of software to let us upload files in Rails.

Open Gemfile in the project directory using your text editor and add

gem 'carrierwave'

In the terminal run:

bundle

Now we can generate the code for handling uploads. In the terminal run:

rails generate uploader Picture

At this point you need to restart the Rails server process in the terminal.

Hit Ctrl+C in the terminal to quit the server. Once it has stopped, you can press the up arrow to get to the last command entered, then hit enter to start the server again.

This is needed for the app to load the added library.

Open app/models/place.rb and add

mount_uploader :picture, PictureUploader

Open app/views/places/_form.html.erb and change

<%= f.text_field :picture %>

to

<%= f.file_field :picture %>

Sometimes, you might get an TypeError: can’t cast ActionDispatch::Http::UploadedFile to string.

If this happens, in file app/views/places/_form.html.erb change the line

<%= form_for(@place) do |f| %>

to

<%= form_for @place, :html => {:multipart => true} do |f| %>

Now if you run your server, and try adding a new place with a picture, you’ll notice that the picture doesn’t look nice because it only shows a path to the file. Let’s fix that.

Open app/views/places/show.html.erb and change

<%= @place.picture %>

to

<%= image_tag(@place.picture_url, :width => 600) if @place.picture.present? %>

Now refresh your browser to see what changed.

Coach: Talk a little about HTML.

Coach: Explain what specifying the image width in HTML at the end of Step 4 does and how it differs from resizing images on the server.

Installing ImageMagick

Coach: What is ImageMagick and how is it different from libraries/gems we used before?

Open Gemfile in the project and add

gem 'mini_magick', '3.5.0'

In the Terminal run:

bundle

Telling our app to create thumbnails when an image is uploaded

Open app/uploaders/picture_uploader.rb and find the line that looks like this:

  # include CarrierWave::MiniMagick

Remove the # sign.

Coach: Explain the concept of comments in code.

Below the line you just changed, add:

version :thumb do
process :resize_to_fill => [50, 50]
end

The images uploaded from now on should be resized, but the ones we already have weren’t affected. So edit one of the existing places and re-add a picture.

Displaying the thumbnails

To see if the uploaded picture was resized open app/views/places/index.html.erb. Change the line

<td><%= place.picture %></td>

to

<td><%= image_tag place.picture_url(:thumb) if place.picture? %></td>

Take a look at the list of ideas in the browser to see if the thumbnail is there.