File Upload using Carrierwave in Rails 5.1

In this article, we will use Carrierwave 1.1.0 for file upload in Rails 5.1.

Create .railsrc in your home folder.


You can specify the options provided by rails help command in .railsrc file and these options will be used when you create a new rails project.

rails new cwave

Add the gem to Gemfile.

gem 'carrierwave', '~> 1.0'



Generate the file uploader:

rails generate uploader Image

The generated file uploader in uploads directory:

class ImageUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir

Generate the model with field for file upload called image.

rails g model product name image

Migrate the database:

rails db:migrate

You can now make the product model use the image uploader:

class Product < ApplicationRecord
  mount_uploader :image, ImageUploader

The form partial:

<%= form_with(model: product, local: true, :html => {multipart: true}) do |form| %>
  <% if product.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(product.errors.count, "error") %> prohibited this product from being saved:</h2>
      <% product.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
  <% end %>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name, id: :product_name %>

  <div class='field'>
    <%= form.file_field :image %>

  <div class="actions">
    <%= form.submit %>
<% end %>

The new page:

<h1>New Product</h1>

<%= render 'form', product: @product %>
<%= link_to 'Back', products_path %>

The show page:

<p id="notice"><%= notice %></p>
  <%= %>

<%= image_tag @product.image_url %>

The index page:

<p id="notice"><%= notice %></p>
      <th colspan="3"></th>
    <% @products.each do |product| %>
        <td><%= %></td>
    <% end %>
<%= link_to 'New Product', new_product_path %>

You will now be able to upload images when you create the product.

Related Articles

Software Compatibility Best Practices

I spoke to some of the most talented and experienced software developers. I have created a guide that is filled with valuable insights and actionable ideas to boost developer productivity.

You will gain a better understanding of what's working well for other developers and how they address the software compatibility problems.

Get the Guide Now