Add picture uploads

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 the following line to the list of gems:

gem 'carrierwave'

Coach: Explain what libraries are and why they are useful. Describe what open source software is.

Hit CTRL-C in the terminal to quit the server. Once it has stopped, in the terminal run:

bundle install

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

rails generate uploader Picture

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

rails server

This is needed for the app to load the added library. Open app/models/idea.rb and under the first line add

mount_uploader :picture, PictureUploader


Open app/views/ideas/_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/ideas/_form.html.erb change the line

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

to

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

In your browser, add new idea with a picture. When you upload a picture it doesn’t look nice because it only shows a path to the file, so let’s fix that. Open app/views/ideas/show.html.erb and change

<%= @idea.picture %>

to

<%= image_tag(@idea.picture_url) if @idea.picture.present? %>

Now refresh your browser to see what changed.

Coach: Talk a little about HTML.

Exercise 1

In the ‘ideas list’ page, it still shows the path to the picture instead of the picture itself. Can you fix it?

Exercise 2

The images that were added are currently very big. With the help of your coach, make them smaller using CSS.

continue