Paperclip: Attaching Files in Rails

Installation

Paperclip is distributed as a gem, which is how it should be used in your app. It’s technically still installable as a plugin, but that’s discouraged, as Rails plays well with gems.

Include the gem in your Gemfile:

gem "paperclip"

next open your terminal

bundle install

Quick Start

In your model:

class User < ActiveRecord::Base
  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end

and create new file migrations:

class AddAvatarColumnsToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :avatar_file_name,    :string
    add_column :users, :avatar_content_type, :string
    add_column :users, :avatar_file_size,    :integer
    add_column :users, :avatar_updated_at,   :datetime
  end

  def self.down
    remove_column :users, :avatar_file_name
    remove_column :users, :avatar_content_type
    remove_column :users, :avatar_file_size
    remove_column :users, :avatar_updated_at
  end
end

In your edit and new views:

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

In your show view:

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

To detach a file, simply set the attribute to nil:

@user.avatar = nil
@user.save
Advertisements

About me
Interested about Ruby on Rails

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: