Deviseで作成したユーザーにプロフィール画像を割り当てる(CarrierWave)
(DeviseでUserのログインを実装してる前提)
CarrierWave使ってると多分エラー出る
Gemを追加
code:Gemfile
# 以下追加
gem 'carrierwave'
gem 'mini_magick'
Uploaderを作る
code:bash
rails g uploader Avatar
UploaderをUserにマウント
code:app/models/user.rb
mount_uploader :avatar, AvatarUploader # 追加
# カラム名 # Uploader名
Usersテーブルにプロフィール画像のカラムがない場合追加する
code:bash
rails g migration AddColumnsToUsers avatar
code:db/migrate/01234567891011_add_columns_to_users.rb
class AddUserAvatar < ActiveRecord::Migration
def change
add_column :users, :avatar, :string
end
end
code:bash
rails db:migrate
ストロングパラメータの設定(下はサインアップの場合、エディットなどでもアップロードする場合は追記する)
code:app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
before_action :configure_permitted_parameters, if: :devise_controller? # 追加
# 以下追加
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: :avatar) end
end
app/controllers/users/registrations_controller.rbに書いてもいいと思う、というか僕はこっち派rhiroe.icon
code:bash
rails g devise:controllers Users
code:app/controllers/users/registrations_controller.rb
# トカゲちゃんの書いたコードというか実際のファイル(多分その方がわかりやすい)
# アイコン画像のアップロードの他にヘッダー画像アップロード、ユーザーネーム、ユーザープロフィールも追加してます
# 元々色々コメントアウトされてるから必要に応じてコメントアウト外して使おう
# frozen_string_literal: true
class Users::RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: :create before_action :configure_account_update_params, only: :update # GET /resource/sign_up
# def new
# super
# end
# POST /resource
# def create
# super
# end
# GET /resource/edit
# def edit
# super
# end
# PUT /resource
# def update
# super
# end
# DELETE /resource
# def destroy
# super
# end
# GET /resource/cancel
# Forces the session data which is usually expired after sign
# in to be expired now. This is useful if the user wants to
# cancel oauth signing in/up in the middle of the process,
# removing all OAuth session data.
# def cancel
# super
# end
def thanks # これはサインアップした時にメール送ったよってページを表示させるために追加したもの(無視して)
end
protected
# If you have extra params to permit, append them to the sanitizer.
def configure_sign_up_params
end
# If you have extra params to permit, append them to the sanitizer.
def configure_account_update_params
end
# The path used after sign up.
# def after_sign_up_path_for(resource)
# super(resource)
# end
# The path used after sign up for inactive accounts.
def after_inactive_sign_up_path_for(resource)
users_thanks_path
end
end
僕はサインアップの時は画像アップロードせずに全てのユーザーにデフォルト画像を割り当ててます。
後ほどユーザー編集でアイコンとかアップロードして編集してもらうスタンスです。rhiroe.icon
あとは確認して各々調整して