Building the photo controller and view

We want RESTful URLs for our photo resource. Here is the routes.rb file.

1PhotoGallery::Application.routes.draw do
2  resources :photos
3end

It is time to create the contorller.

1$ rails generate controller photos

The controller

 1class PhotosController < ApplicationController
 2  def new
 3    @photo = Photo.new
 4  end
 5
 6  def create
 7    @photo = Photo.new params[:photo]
 8    if @photo.save
 9      redirect_to @photo
10    else
11      render :new
12    end
13  end
14end

views/photos/new.html.erb

 1<%- form_for @photo, html: { :multipart => true } do |f| %>
 2  <p>
 3    <%= f.label :title %> <br>
 4    <%= f.text_field :title %>
 5  </p>
 6
 7  <p>
 8    <%= f.label :file %> <br>
 9    <%= f.file_field :file %>
10  </p>
11
12  <p>
13    <%= f.submit 'Upload Photo' %>
14  </p>
15<%- end %>

Let’s try the function in browser with the following steps.

  1. In terminal, in the current project, run rails server.
  2. Open http://0.0.0.0:3000/photos/new in web browser.
  3. Select an image file and put in the title.
  4. Click the ‘Upload Photo’ button.
  5. Now we should see an error of NoMethodError.
  6. If we check the URL, it is redirected to the photo showing URL with the newly created photo ID.
  7. This is normal because we haven’t implemented the show method in controller yet.

No method error

Then we add the show feature

The photos_controller.rb

1def show
2  @photo = Photo.find params[:id]
3end

And its related view: views/photos/show.html.erb

1<%= image_tag @photo.file.url(:medium) %> <br>
2<%= @photo.title %>

Since the edit form shares the same code from the create form, we will extract the form into a common file.

Move the entire form_for block to a new file: views/photos/_form.html.erb

Now the views/photos/new.html.erb becomes

1<h1>Creating New Photo </h1>
2<%= render 'form' %>

And the views/photos/edit.html.erb file

1<h1>Edit Photo </h1>
2Existing image: <br>
3<%= image_tag @photo.file.url(:medium) %>
4
5<%= render 'form' %>

Optionally we may want to let site admin edit the photo from the user interface, we can do that by adding a link to the edit path in the views/photos/show.html.erb file.

1<%= link_to 'Edit', edit_photo_path(@photo) %>

And the edit and update controller method in the photos_controller.rb file.

 1def edit
 2  @photo = Photo.find params[:id]
 3end
 4
 5def update
 6  @photo = Photo.find params[:id]
 7
 8  if @photo.update_attributes params[:photo]
 9    redirect_to @photo
10  else
11    render :edit
12  end
13end

Let’s try the function in browser and we should be able to create and edit photos. Here is a screenshot of the editing screen:

Edit photo

What’s next? We’re going to take a look at “Using partial file”.

overlaied image when clicked on thumbnail

Makzan | Ruby on rails 101 | Table of Content