Uploading Files with Refile

Episode #13 by Teacher's Avatar David Kimura

Summary

Refile is a modern file upload library for Ruby applications. It is simple, yet powerful. This episode covers the basics of uploading and displaying images. Next episodes will cover protecting files and progress bars.
rails uploads 3:17

Resources

Summary

# Gemfile
    gem "refile", require: "refile/rails"
    gem "refile-mini_magick"

# bash
    brew install imagemagick # OS X
    sudo apt-get install imagemagick # Ubuntu

    rails generate migration add_profile_image_to_users profile_image_id:string
    rake db:migrate

# app/models/user.rb
    class User < ActiveRecord::Base
      attachment :profile_image, type: :image
      attachment :resume, extension: ["pdf", "doc"]
    end

# app/views/users/_form.html.erb
    <%= form_for @user do |f| %>
      <%= f.attachment_field :profile_image %>
    <% end %>

# app/controllers/users_controller.rb
    def user_params
      params.require(:user).permit(:profile_image)
    end

# app/views/users/show.html.erb
    <%= image_tag attachment_url(@user, :profile_image, :fill, 300, 300, format: "jpg") %>