Building the photo model

We always define the model first. As a gallery, our photo model will contian the attachment and a title describing it. The attachment will be done by the paperclip gem. Let’s create the photo model with titie only by the following commands.

$ rails generate model photo title:string
    invoke  active_record
    create    db/migrate/20131003143245_create_photos.rb
    create    app/models/photo.rb
    invoke    test_unit
    create      test/unit/photo_test.rb
    create      test/fixtures/photos.yml

$ rake db:migrate
==  CreatePhotos: migrating =======================
-- create_table(:photos)
   -> 0.0056s
==  CreatePhotos: migrated (0.0059s) ==============

Now it is time to attach a file to our photo model.

Let’s add the paperclip gem to the Gemfile.

gem 'paperclip'

Then bundle install it

$ bundle install

If the imagemagick isn’t installed yet, use homebrew to install it with the following command.

$ brew install imagemagick

Now it is time to generate a paperclip attchment to our photo model. Run the following paperclip generation command.

$ rails generate paperclip photo file
      create  db/migrate/20131003150131_add_attachment_file_to_photos.rb

The generator creates a database migration, that we need to push it to the database.

$ rake db:migrate
==  AddAttachmentFileToPhotos: migrating ============================
-- change_table(:photos)
   -> 0.0033s
==  AddAttachmentFileToPhotos: migrated (0.0035s) ===================

And now we can map the database in the model. Make the photo.rb file matches the following snippet.

class Photo < ActiveRecord::Base
  attr_accessible :title, :file
  has_attached_file :file, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
end

Note: We can create different resize options in the styles option hash. Take the following option as example, it defined 4 resize options so there are total 5 sizing including the original dimension.

has_attached_file :file,
  styles: {
    large: "1000x1000",
    medium: "800x800",
    thumb: "300x300",
    square: "300x100#" }, default_url: "/images/:style/missing.png"

Note2: The style dimension option is a string which follow exactly the ImageMagick germetry format:

> means resizing to make width and/or height matching the given dimension.

# means cropping to fit the exact dimension.

What’s next? We’re going to take a look at “Building the photo controller and view”.

overlaied image when clicked on thumbnail

Makzan | Ruby on rails 101 | Table of Content