Integrating PaperClip to a Rails Model

Include the gem in ‘Gemfile’

gem "paperclip", "~> 3.0"

1.  Add a rails migration to the model

      rails g migration addAvatarColumnToMenu
      invoke  active_record
      create db/migrate/20131113072946_add_avatar_column_to_menu.rb

2.  Edit your migration

 class AddAvatarColumnToMenu < ActiveRecord::Migration
   def self.up
     change_table :menus do |t|
        t.attachment :avatar
   def self.down
      drop_attached_file :menus, :avatar

3.  Add the following to your model

class Menu < ActiveRecord::Base
  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"

4.  Run the migration

 rake db:migrate
==  AddAvatarColumnToMenu: migrating ============================
-- change_table(:menus)
-> 0.5326s
==  AddAvatarColumnToMenu: migrated (0.5328s) ===================

5.  You should see the 4 columns added if you run “rails console”

avatar_file_name: string, avatar_content_type: string, avatar_file_size: integer, avatar_updated_at: datetime

6.  Add this to your “new” and “update” views

<%= form_for @menu, :url => menus_path, :html => { :multipart => true } do |form| %>
  <%= form.file_field :avatar %>
<% end %>

7.  Add this to the ‘show’ view

<%= image_tag @menu.avatar.url %>
<%= image_tag @menu.avatar.url(:medium) %>
<%= image_tag @menu.avatar.url(:thumb) %>

8.  Restart the server to get the new table data set.


One thought on “Integrating PaperClip to a Rails Model

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s