Uploading files

From ruby-toolbox, we found two popular gems for uploading files:

  1. paperclip
  2. carrierwave

Their difference:

  1. paperclip: must bound to model.
  2. carrierwave: indepentent to model.

We’ll use the paperclip gem.

Note: For detial and most updated gem usage, please check the official doc. (http://github.com/thoughtbot)

Note2: Two blog posts on paperclip gem.

  1. http://blog.railsthemes.com/2013/05/14/my-favorite-gem-paperclip/
  2. http://bcjordan.github.io/posts/rails-image-uploading-framework-comparison/

We need to install imagemagick for image resizing feature.

$ brew install imagemagick

Add the gem to Gemfile.

gem "paperclip"

Then call bundle install gems in system.

$ bundile install

Assume now every job comes with a marketing poster, user can upload any images file as poster image for each job.

We can do that by declaring the poster attachment in the job model. Add the following to models/job.rb file.

has_attached_file :poster, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"

How about the database changes? We need several more columns to the job table. The migration can be generated by paperclip gem with the following command.

$ rails generate paperclip job poster
$ rake db:migrate

Then we add the new poster column to the job form by using the file_field helper.

<%= form_for @job, html: { multipart: true } do |f| %>
  <%= f.file_field :poster %>
<% end %>

The multipart is required to send file in a POST request.

How about displaying the poster image?

<%= image_tag @job.poster.url %>
<%= image_tag @job.poster.url(:medium) %>
<%= image_tag @job.poster.url(:thumb) %>

What’s next? We’re going to take a look at “Ruby on Rails 101 – Chapter 5”.

overlaied image when clicked on thumbnail

Makzan | Ruby on rails 101 | Table of Content