Using paperclip for image attachments in rails

Advantage to using paperclip: you don’t have to create separate model for images and then create a join relationship like with attachment_fu

What you’ll need:
- the paperclip plugin: run the following from your terminal in your rail’s project root folder:

script/plugin install git://github.com/thoughtbot/paperclip.git

Useful tutorials:
- Paperclip project page
- Paperclip original tutorial
- Paperclip more useful tutorial

How to:

1. Create a new migration file: script/generate migration add_images_to_flowers and rake db:migrate

class AddImageToFlowers < ActiveRecord::Migration
  def self.up
    add_column :flowers, :image_file_name, :string
    add_column :flowers, :image_content_type, :string
    add_column :flowers, :image_file_size, :integer
  end

  def self.down
    remove_column :flowers, :image_file_size
    remove_column :flowers, :image_content_type
    remove_column :flowers, :image_file_name
  end
end

2. Change your form to use multipart. (I don’t see why http just doesn’t default to multipart with its forms. It’s seems a little ridiculous to have to add multi-part)

	<% form_for [:admin, @flower], :html => { :multipart => true } do |f| %> #if you put your new/edit under admin/flowers_controller.rb
	or
	<% form_for @flower, :html => { :multipart => true } do |f| %>

3. Add the file field to the form

<%= f.label :image %>
<%= f.file_field :image %> #as you can see if uses the pre-name to the above migration fields 'image'. This is one smart plugin.

4. In your model add the following

class Flower < ActiveRecord::Base

  # Paperclip
  has_attached_file :image,
    :styles => {
      :thumb=> "100x100#",
      :small  => "150x150>",
      :medium => "300x300>" }

end

5. Now try uploading an image and check your database to see that it got added. You’ll also see that in your public view it added a folder called images (plural of image) with a subfolder defined by the id of the post, and with more subfolders for the different sizes of your image as you specified in the above model (thumb, small, medium).

Picture 1.png

Pretty darn cool, if you ask me.

This is a great tool for simple single image adding to a model.

6. Add it to your views. This is pretty easy just call the following:

<%= image_tag @flower.image.url %>
<%= image_tag @flower.image.url(:thumb) %>
<%= image_tag @flower.image.url(:small) %>
<%= image_tag @flower.image.url(:medium) %>

I think you get the idea.

Comments

  1. Scott | August 22, 2008

  2. Scott | August 22, 2008

    Update: Dealing w/ PDFs instead of images. Speeding up paperclip when this happens. http://devblog.rorcraft.com/2008/8/1/patching-paperclip-to-only-thumbnail-images

  3. Scott | August 22, 2008