To Examples

PetPhotoUpload Example

Reference: Dumbill and Gruber, Learning Rails 3, O'Reilly,

Summary: Extending a Rails application for uploading and displaying images involves five steps: (1) run a migration to add a field to the database, (2) augment the model, (3) add code to display the image in the show view, (4) modify the input form so it can accept the uploaded photo, (5) modify the controller to whitelist the photo received from the File Upload control.

Directions

  1. Create a Rails project with name PetPhotoUpload.
  2. Generate a scaffold named Pet with these data fields:
    Field Datatype
    name string
    animal_type string
    owner string
  3. Generate a migration that adds the new field extension to the model:
    rails g migration AddExtensionToPet extension:string
    
  4. Check to see that the created migration file add_extension_to_pet in PetPhotoUpload/db/migrations looks like this:
    class AddExtensionToPet < ActiveRecord::Migration
      def change
        add_column :pets, :extension, :string
      end
    end
    
  5. Rake the migration files with rake db:migrate.
  6. Use this source code for the Pet model file: PetPhotoUpload/app/models/Pet.rb.
  7. In the show view for Pet, add this code between the displayed information for owner and the links at the bottom:
    <p>
      <strong>Photo:</strong><br />
      <% if @pet.has_photo? %>
        <%= image_tag @pet.photo_path %>
      <% else %>
        No photo.
      <% end %>
    </p>
    
  8. In the input form in PetPhotoUpload/app/views/pets/_form.html.erb:
    1. Between the owner textfield and the submit button, insert this code for the file upload control:
      <div class="field">
        <%= f.label :photo %><br />
        <%= f.file_field :photo %>
      </div>
      
    2. Replace the form_for tag with
      <%= form_for(@pet, html: { multipart: true }) do |f| %>
      
  9. At the bottom of the pets controller, add :photo to the list of input fields permitted by the model:
    # Never trust parameters from the scary internet, 
    # only allow the white list through.
    def pet_params
      params.require(:pet).permit(:name, :animal_type, :owner)
    end
    
    Change the params.require method call to
    params.require(:pet).permit(:name, :animal_type, :owner, :photo)
    
  10. View the index view with this URL:
    http://localhost:3000/pets
    
  11. Some pet test images. Click on any thumbnail for a larger image.