Attachment, Attachments, Attached

You need Attachments everywhere in Internet World. Its when you are writing a mail, creating your profile at some social network website, uploading images at Photograph managing sites, so on & so on. Internet world is incomplete without attachments. So, attachment can be an image, a video file, audio file, a text document(actually if we see, every file is a Text file in computer science). Lets see how this thing is done in Rails

You can use a plugin called Paperclip which is written by Jon Yurek. It needs 3 columns in the database table you are uploading the file – file name, content type & file size. But where the uploaded file will go? Don’t worry Paperclip will save these file in RAILS_ROOT/public/system folder of your Rails application. So, it will just maintain Information about your uploaded file in Database & your actual file resides in your system folder.

How do you implement Paperclip in your Rails Application?

Step 1: You need to install Plugin for Paperclip

gem install paperclip

Step 2: Add the following in your model

class User < ActiveRecord::Base
   has_attached_file :somefile
end

Step 3: Add 3 more columns(filename, filetype, filesize) to the related table with attribute name as prefix, mean the names of new columns will be somefile_file_name, somefile_content_type & somefile_file_size. Create active record migration,

class AddPdfToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :somefile_file_name, :string
    add_column :users, :somefile_content_type, :string
    add_column :users, :somefile_file_size, :integer
  end
  def self.down
    remove_column :users, :somefile_file_name
    remove_column :users, :somefile_content_type
    remove_column :users, :somefile_file_size
  end
end

Step 4: Update database using  rake db:migrate

Note: rake db:migrate will Update the database of the current environment to the latest version

Step 5: Controller

No changes at Controller level

Step 6: At View level

<% form_for :user, :html => { :multipart => true } do |f| %>
<%= f.file_field :somefile%>
<% end %>

Now your are done with configuration of Paperclips in your rails application for uploading files

Advertisements
This entry was posted in Ruby on Rails and tagged , . Bookmark the permalink.

One Response to Attachment, Attachments, Attached

  1. Gautam Rege says:

    Pankaj,
    Could you also detail out options for has_attached_file like style and its various options.

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