はじめに
CarrierWaveを使用して、プロフィール画像を設定した際躓いたので、備忘録として残します。
前提
- マイページは作成済み
- Userモデルにprofile_imageカラムは追加済み
- ログイン機能(アカウント登録等)はdeviseで実装
(スタイル調整は含まれていません。)
環境開発
Mac
Ruby 2.7.2
Rails 6.1.3.2
carrierwave 2.0
完成イメージ
手順
1.CarrierWaveを導入
- Gemfileにgemを追記
gem 'carrierwave', '~> 2.0'
バージョン2.0以降、CarrierWaveにはRails5.0以降とRuby2.2以降が必要です。Rails 4を使用している場合は、1.xを使用する必要があります。
- ターミナルからインストールする
$ bundle install
- サーバーの再起動をおこなう
$ rails c
2.CarrierWaveのアップローダーを作成
-
app/uploaders/image_uploader.rb
ファイルを作成
$ rails g uploader image
3.実装したいクラス(今回はUser)に以下のコードを追加
mount_uploader :profile_image, ImageUploader
これにより、Userモデルのprofile_imageカラムと、先ほど作成したアップローダーImageUploaderと紐付けができる。
4.Strong Parameterにprofile_imageカラムを追加
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :profile_image])
end
end
これを追加していないと、profile_imageのデータを取得できないので、注意!
5.アカウント登録画面に、ファイル選択ボックスを追加
<div class="form-group">
<%= f.label :profile_image %><br/>
<%= f.file_field :profile_image %>
</div>
下記のようにアカウント登録時に、「ファイルを選択」を表示できる
6.Viewの設定
<p>MyPage <%= @user.name %></p>
<% if @user.profile_image? %>
<%= image_tag @user.profile_image.url %>
<% end %>
7.日本語訳を変更(devise使用している場合のみ!)
※作成していない場合は、ターミナルで下記のコマンドを実施して、追加して下さい。
$ rails g devise:i18n:locale ja
8.アカウント登録画面に、ファイル選択ボックスを追加
<div class="form-group">
<%= f.label :profile_image %><br/>
<%= f.file_field :profile_image %>
</div>
9.Strong Parameterにprofile_imageカラムを追加
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
def configure_permitted_parameters
# アカウント登録時に許可
devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :profile_image])
# アカウント編集時に許可
devise_parameter_sanitizer.permit(:account_update, keys: [:name, :profile_image])
end
end
10.アカウント編集画面で、現在選択しているプロフィール画像を表示
<div class="form-group">
<%= f.label :profile_image %><br/>
# ココを追加↓
<%= image_tag @user.profile_image.url if @user.profile_image? %>
<%= f.file_field :profile_image %>
</div>
11.画像登録していなユーザーは、デフォルトで画像を表示する
-
app/uploaders/image_uploader.rb
の設定
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# ↓ココをコメントアウトする
def default_url(*args)
# For Rails 3.1+ asset pipeline compatibility:
ActionController::Base.helpers.asset_path("fallback/" +[version_name, "default.png"].compact.join('_'))
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
end
<% if @user.profile_image? %>
<%= image_tag @user.profile_image.url %>
<% else %>
<%= image_tag("default.png") %>
<% end %>
※今回のように、app/assets/images/default.png
とする場合は、image_tag
ヘルパーメソッドを使用しましょう! タグだと表示できない不具合はあるみたいです!
12.画像を加工する(※デフォルト画像は、元々200x250の大きさです。)
-
imagemagick
を導入するため、ターミナルで下記コマンドを実施
$ brew install imagemagick
$ brew link --force imagemagick
※インストール済みかどうかが分からない場合は,ターミナルから brew list | grep imagemagick
を実行。 imagemagick が表示されればインストール済みです。
-
MiniMagick
をGemに導入
# Gemfileに追加
gem 'mini_magick'
$ bundle install
rails cで、サーバーを再起動しましょう。
# 次の箇所のコメントアウトを解除
include CarrierWave::MiniMagick
- 今回は、200x200に設定したいので、下記を追加
process resize_to_fit: [200, 200]
まとめ
ここまで、読んで下さってありがとうございます!色々デフォルト画像の所は、特につまってしまったので、同じように悩んでいる方の参考となると幸いです