Use CarrierWave to set a user's profile picture

procedure

  1. Add Gemfile
gem 'carrierwave'
$ bundle install
  1. Generate Uploader

uploaders / image_uploader.rb is generated.

$ rails g uploader image
  1. Edit model

Set to use uploader in user.rb.

models/user.rb


class User < ApplicationRecord
  mount_uploader :image, ImageUploader
end
  1. Edit view

new.html


<%= form_with(model: user, local: true) do |form| %>
  <%= form.text_field :name %>
  <%= form.email_field :email %>
  <%= form.password_field :password %>
  <%= form.file_field :image %>
  #Image file information_Let's add the following sentence to temporarily save it in the cache!
  <%= form.hidden_field :image_cache %>
  <%= form.submit %>
<% end %>

index.html


//The image image can be displayed with the following description//
<%= image_tag @user.image.url %>

//When conditional branching with if statement//
<% if @user.image? %>
  <%= image_tag @user.image.url %>
<% else %>
  #If you want to display by default
  <%= image_tag "/assets/default.jpg " %>
<% end %>
  1. Minimagic introduction

gem 'mini_magick'
$ bundle install
  1. Edit the image_uploader.rb file

image_uploader.rb


class AvaterUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick 
  #Resize image
  process resize_to_fit: [100, 100]
end 

that's all

Recommended Posts

Use CarrierWave to set a user's profile picture
How to set and use profile in annotation-based Configuration in Spring framework
A memorandum on how to use Eclipse
[Ruby on Rails] How to use CarrierWave
Steps to set a favicon in Rails
Set the time of LocalDateTime to a specific time
How to implement a circular profile image in Rails using CarrierWave and R Magick
How to use an array for a TreeMap key
Considering a property editor to use with SpringToolSuite (STS)
[Android / Java] Set up a button to return to Fragment
I want to use a little icon in Rails
Steps to set up a VNC server on CentOS 8.3
[Rails 6] How to set a background image in Rails [CSS]
A memo to check when you try to use Lombok