Instructor Lead On-Demand Learning Courses - August Big $10 Sitewide Extravaganza All Pro Web Designs and Udemy are happy to offer this special to you, good only on dates: 08/21-08/31 Act Now!

Rails Image Upload: Using Paperclip in a Rails Application

In the first two parts of this series, I showed you how to enable image uploading in Rails using CarrierWave. In this part, you will see how to do so using Paperclip.

Paperclip is a Ruby gem provided by thoughtbot. It was created to make file attachment very easy. In this tutorial, you will see how to use Paperclip alongside Devise.

Without much talk, let’s get busy.

Paperclip requires the installation of ImageMagick on your machine. You need this for image processing. To install ImageMagick, use any of the steps below, depending on the type of machine you use.

Mac Users:

Instructor Lead On-Demand Learning Courses - August Big $10 Sitewide Extravaganza All Pro Web Designs and Udemy are happy to offer this special to you, good only on dates: 08/21-08/31 Act Now!

brew install imagemagick

Ubuntu users:

sudo apt-get install imagemagick

Rails Application Generation

Use your terminal to generate a new application.

rails new paperclip

Open up your Gemfile and add the necessary gems:

gem 'paperclip'

gem 'devise'

Run bundle install when you are done.

Devise Setup

From your terminal, install devise using the command below:

rails generate devise:install

When that is done, you can now generate your User model:

rails generate devise User

Migrate your database after.

rake db:migrate

Generate your devise views.

rails generate devise:views

Using your text editor, navigate to app/views/layouts/application.html.erb and add the following code just above the yield block.

#app/views/layouts/application.html.erb

<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>

Paperclip Integration

Due to security reasons, we have to permit parameters in the Devise controller. Thanks to the awesome team behind Devise, doing this is easy.

Open up app/controllers/application_controller.rb and paste in the following lines of code.

#app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.

  protect_from_forgery with: :exception
  
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, :remember_me, :avatar, :avatar_cache) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :password, :password_confirmation, :current_password, :avatar) }
  end
end

Open up your User model and make it look like this:

#app/models/user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_attached_file :avatar, styles: { medium: "300x300", thumb: "100x100" }
  validates_attachment_content_type :avatar, content_type: /Aimage/.*Z/
end

You need to add an avatar column to your Users table. There is a rails command that makes this possible from your terminal.

rails generate migration add_avatar_to_users

That will create a new migration in db/migrate. Open it up and paste the below code:

class AddAvatarToUsers < ActiveRecord::Migration
  def up
    add_attachment :users, :avatar
  end

  def down
    remove_attachment :users, :avatar
  end
end

Run your migration

rake db:migrate

Add Avatar to Devise Forms

You will edit your registration new form app/views/devise/registrations/new.html.erb and edit the form app/views/devise/registrations/edit.html.erb to what I have below:

#app/views/devise/registrations/new.html.erb

<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { multipart: true }) do |f| %>
  <%= devise_error_messages! %>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>

  <div class="field">
    <%= f.label :password %>
    <% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.file_field :avatar %>
  </div>

  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>
#app/views/devise/registrations/edit.html.erb

<h2>Edit <%= resource_name.to_s.humanize %></h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
  <%= devise_error_messages! %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>

  <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
    <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
  <% end %>

  <div class="field">
    <%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.file_field :avatar %>
  </div>

  <div class="field">
    <%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
    <%= f.password_field :current_password, autocomplete: "off" %>
  </div>

  <div class="actions">
    <%= f.submit "Update" %>
  </div>
<% end %>

<h3>Cancel my account</h3>

<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>

<%= link_to "Back", :back %>

Kick off your browser and check out what you have.

For a standard application, you might want to check if a user who wants to edit his or her profile already has an avatar uploaded. This is easy to implement in your registration edit file.

Open up the registration edit file and make it look like this:

#app/views/devise/registrations/edit.html.erb

<h2>Edit <%= resource_name.to_s.humanize %></h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
  <%= devise_error_messages! %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>

  <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
    <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
  <% end %>

  <div class="field">
    <%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.file_field :avatar %>

    <% if @user.avatar? %>
      <%= image_tag @user.avatar.url(:thumb) %>
    <% end %>
  </div>

  <div class="field">
    <%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
    <%= f.password_field :current_password, autocomplete: "off" %>
  </div>

  <div class="actions">
    <%= f.submit "Update" %>
  </div>
<% end %>

<h3>Cancel my account</h3>

<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>

<%= link_to "Back", :back %>

Can you see what changed?

In the above code, there is a conditional statement to check if an avatar already exists for a user using the line <% if @user.avatar? %>. If this returns true, the next line gets run, else it does not.

Security Validations

Validation is always important when enabling uploading features in your web application. Paperclip comes with measures to secure your application.

You can use any of the validations below in your model.

class User < ActiveRecord::Base
  has_attached_file :avatar
  # Validate content type
  validates_attachment_content_type :avatar, content_type: /Aimage/
  # Validate filename
  validates_attachment_file_name :avatar, matches: [/pngZ/, /jpe?gZ/]
  # Explicitly do not validate
  do_not_validate_attachment_file_type :avatar
end

Conclusion

You might want to consider Paperclip as you build your next web application. It has a great team supporting it.

To explore other features not covered in this tutorial, check Paperclip’s GitHub page.

Instructor Lead On-Demand Learning Courses - August Big $10 Sitewide Extravaganza All Pro Web Designs and Udemy are happy to offer this special to you, good only on dates: 08/21-08/31 Act Now!

Leave a Reply