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.
Field | Datatype |
---|---|
name | string |
animal_type | string |
owner | string |
rails g migration AddExtensionToPet extension:string
class AddExtensionToPet < ActiveRecord::Migration def change add_column :pets, :extension, :string end end
<p> <strong>Photo:</strong><br /> <% if @pet.has_photo? %> <%= image_tag @pet.photo_path %> <% else %> No photo. <% end %> </p>
<div class="field"> <%= f.label :photo %><br /> <%= f.file_field :photo %> </div>
<%= form_for(@pet, html: { multipart: true }) do |f| %>
# Never trust parameters from the scary internet, # only allow the white list through. def pet_params params.require(:pet).permit(:name, :animal_type, :owner) endChange the params.require method call to
params.require(:pet).permit(:name, :animal_type, :owner, :photo)
http://localhost:3000/pets
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |