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.
Gemfile in the project directory using your text editor and add
In the terminal run:
Now we can generate the code for handling uploads. In the terminal run:
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.
app/models/place.rb and add
app/views/places/_form.html.erb and change
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
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.
app/views/places/show.html.erb and change
Now refresh your browser to see what changed.
Talk a little about HTML.
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.
- macOS: run
brew install imagemagick. If you don’t have the brew command, you can install Homebrew here.
- Windows: download and run the ImageMagick installer (use the first download link). Reopen your Rails Command Shell afterwards.
Linux: On Ubuntu and Debian, run
sudo apt-get install imagemagick. Use the appropriate package manager instead of
apt-getfor other distributions.
What is ImageMagick and how is it different from libraries/gems we used before?
Gemfile in the project and add
In the Terminal run:
Telling our app to create thumbnails when an image is uploaded
app/uploaders/picture_uploader.rb and find the line that looks like
Explain the concept of comments in code.
Below the line you just changed, add:
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
Take a look at the list of ideas in the browser to see if the thumbnail is there.
Want to learn more? View more guides!