Skip to content
Evan Prothro edited this page Feb 5, 2014 · 1 revision

Overview

Add a single avatar to your user model using paperclip.

Tutorial

Add fields in persistence layer

rails generate paperclip user avatar && rake db:migrate

Configure paperclip attachment on model

  1. Add the following to user.rb
  # square: resize to 50x50, cropping to the center(#)
  # thumb: resize to 100px wide, keeping aspect ratio
  # large: resize up to 500px wide without stretching, keeping aspect ratio
  # options: compress 10%, strip meta tags, save as progressive (if jpg)
  has_attached_file :avatar, styles: {tiny_square: "50x50#", thumb: "100", large: "500>"},
                             convert_options: { all: '-quality 90 -strip -interlace Plane'},
                             s3_headers: { "x-amz-server-side-encryption" => "AES256" },
                             :default_url => ActionController::Base.helpers.asset_path('anonymous_user.jpg')
  1. Create an anonymous user image in app/assets/images/anonymous_user.jpg

Show the avatar in the navigation bar

  1. Modify app/views/layouts/_navigation.html.haml so the dropdown trigger contains the image:
%li.has-dropdown
  %a
    = image_tag current_user.avatar.url(:tiny_square), class: 'avatar'
    = current_user
  1. Style the avatar to your liking in app/assets/stylesheets/partials/_navigation.sass:
.avatar
  width: 36px
  float: left
  margin-top: 5px
  margin-right: 10px
  position: relative

  -webkit-border-radius: 50%
  -moz-border-radius: 50%
  border-radius: 50%

Modify your user registration edit to allow user to upload image

  1. Add a file field for the avatar to the existing form at /app/views/registrations/edit.html.haml:
  .field
    = f.label :avatar
    .text-center
      = image_tag resource.avatar.url(:large)
      = f.file_field :avatar, class: 'secondary button'
  1. Modify app/controllers/registrations_controller.rb to allow the avatar parameter:
class RegistrationsController < ::Devise::RegistrationsController
  before_filter :configure_permitted_parameters, only: [:update]

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:account_update) << :avatar
  end
end

Next Steps

Use S3 image uploader to buffer slow clients

Convert images using a background worker with delayed_paperclip