Uploading Images

Extending a Rails application for uploading and displaying images calls for four steps:

  1. Adding a field to the database
  2. Augmenting the model
  3. Modifying the form
  4. Writing display code

The method presented here involves storing the images in public folder of the web application. It is adapted from the method presented in Learning Rails (pp. 123 - 133).

Other approaches store the image in the database.

Adding a field to the database

The database table requires a field that holds the extension of the file name (e.g. png, jpg, gif). The example presented here assumes that the field name is called extension and is stored as a string. The image file will be stored using the record id (primary key).

Augmenting the model

Additional model code is required so that the controller can store the photo (using the virtual photo attribute as part of the model). The model then stores the extension in the database and saves the file in the photo folder.

Here is an example model file.

Modifying the form

The form tag needs to be expanded to state that it is a multi-part form:

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

    

The file field tag allows a user to upload a file in a form:

    
    <%= f.label :photo %><br />
    <%= f.file_field :photo %>
    

Writing display code

Writing a helper is useful for displaying the image. This code can be placed in one of the files in the helpers folder:

  def display_photo(item)
    if item.has_photo?
      image_tag item.photo_path
    else
       "No photo."
    end
  end

With this helper, the image can be displayed in a view as follows:

  <%= display_photo animal %>

where animal is the name of the data object associated with the image.