gem 'carrierwave'
$ bundle install
uploaders / image_uploader.rb is generated.
$ rails g uploader image
Set to use uploader in user.rb.
models/user.rb
class User < ApplicationRecord
mount_uploader :image, ImageUploader
end
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 %>
gem 'mini_magick'
$ bundle install
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