[Ruby] [Rails] Save images using carrierwave

1 minute read

It will be exactly as the title says.

The goal is to display the image.

Introducing gem

Initially put a gem. If you do not specify the version, the latest version will be installed.

Gemfile


gem'carrirewave'

Thank you for your usual support at the terminal.

$ bundle install

Generate uploader file

Next, let’s create the uploader file.

$ rails generate uploader Image
create app/uploaders/image_uploader.rb

Now, I think that image_uploader.rb is generated in app/uploaders.

By the way, Image part is the model name to mount, A descriptive name. I often generate with Image.

image_uploader.rb


class ImageUploader <CarrierWave::Uploader::Base
 # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  # include CarrierWave::MiniMagick
  # process resize_to_fit: [300, 200]

  # version :thumb do
  # process :resize_to_fit => [50, 50]
  # end

  #Omitted below
end

You can make settings related to image upload in this file. For example, you can limit the extension of the uploaded image, resize the image size, and so on.

Write on the model

Mount the file you just created on the model you want to upload images to.

This time, let’s consider the case where you want to register an image in the image column of the hoge model.

hoge.rb


class hoge <ApplicationRecord
  mount_uploader :image, ImageUploader
end

Create a Form to register

Each page will give you the necessary information.

hoges_controller.rb


class ArticlesController <ApplicationController

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(user_params)
    if @article.save
      redirect_to user_path(@article)
    else
      render :new
    end
  end

  private
  def article_params
    params.require(:article).permit(:image)
  end
end

/hoges/new.html


<%= form_with model: @hoge, local: true do %>
    <div class="field">
<%= f.label :image %>
<%= f.file_field :image %> <!-- image is file_field -->
<div class="action">
<%= f.submit %>
</div>
<% end %>

Display of uploaded image

The image display is basically displayed as described below.

<%= image_tag @article.image.url %>
<%= image_tag @article.image.to_s %>

At the end

Thank you for reading to the end. I hope that those who are studying can help a little.