1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CarrierWaveを使って、ユーザーのプロフィール画像を設定する

Last updated at Posted at 2020-05-16

#手順

1.Gemfileの追加

gem 'carrierwave'
$ bundle install

2.Uploaderの生成

uploaders/image_uploader.rbが生成される。

$ rails g uploader image

3.モデルの編集

user.rbでuploaderを使う設定をする。

models/user.rb
class User < ApplicationRecord
  mount_uploader :image, ImageUploader
end

4.ビューの編集

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_cacheに一時保存するために下記の一文も追記しよう!
  <%= form.hidden_field :image_cache %>
  <%= form.submit %>
<% end %>
index.html
// 下記記述でimage画像を表示できる //
<%= image_tag @user.image.url %>

// if文で条件分岐する場合 //
<% if @user.image? %>
  <%= image_tag @user.image.url %>
<% else %>
  # デフォルトで表示したい場合
  <%= image_tag "/assets/default.jpg" %>
<% end %>

5.minimagic導入


gem 'mini_magick'
$ bundle install

6.image_uploader.rbファイルを編集

image_uploader.rb
class AvaterUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick 
  # 画像をリサイズ
  process resize_to_fit: [100, 100]
end 

以上

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?