It will be as the title.
The goal is to display the image.
First, insert a gem. If you do not specify the version, the latest version will be installed.
Thank you for your continued support at the terminal.
$ bundle install
Next, let's create an uploader file.
$ rails generate uploader Image create app/uploaders/image_uploader.rb
You should now have ʻimage_uploader.rb
in ʻapp / uploaders.
By the way, the part of ʻImage` is the model name to mount, A descriptive name. I often generate with Image.
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 image you upload, resize the image, and much more.
Let's mount the file created earlier on the model you want to upload the image.
This time, let's consider the case where you want to register an image in the image column of the hoge model.
class hoge < ApplicationRecord mount_uploader :image, ImageUploader end
I will give you the necessary information on each page.
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
<%= 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 %>
The display of the image is basically displayed by writing as follows.
<%= image_tag @article.image.url %> <%= image_tag @article.image.to_s %>
Thank you for reading to the end. I hope it will help those who are studying.