How to Upload Images in Ruby on Rails

09/20/2021

Contents

In this article, you will learn how to upload images in Ruby on Rails.

Uploading images

There are several ways to upload images in Ruby on Rails. Here’s one common method using the paperclip gem:

  • Install the paperclip gem by adding it to your Gemfile and running bundle install.
  • Generate a migration to add the necessary columns to your model’s table:

    rails generate paperclip ModelName image

    This will generate a migration to add image_file_name, image_content_type, image_file_size, and image_updated_at columns to your model_names table.

  • Run the migration:

    rails db:migrate
  • Add the has_attached_file method to your model, specifying the styles and storage location:

    class ModelName < ActiveRecord::Base
      has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, 
                        default_url: "/images/:style/missing.png", 
                        path: ":rails_root/public/system/:class/:attachment/:id/:style/:filename",
                        url: "/system/:class/:attachment/:id/:style/:filename"
      validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
    end
    

    This will attach an image to your model, and specify that it should be stored in the public/system directory, with the original image and two styles: medium and thumb.

  • In your form view, add a file field for the image:

    <%= form_for @model_name, html: { multipart: true } do |f| %>
      <%= f.label :image %>
      <%= f.file_field :image %>
    <% end %>
    
  • In your controller, permit the image parameter and save the model:

    def create
      @model_name = ModelName.new(model_params)
      if @model_name.save
        redirect_to @model_name
      else
        render 'new'
      end
    end
    
    private
    def model_params
      params.require(:model_name).permit(:image)
    end
    
  • Finally, in your show view, display the image:

    <%= image_tag @model_name.image.url(:medium) %>