1
0

【Rails】Devise Token Authでユーザーのavatarを設定できるようにする方法

Last updated at Posted at 2023-09-15

Active Storageを使用可能にする

以下のコマンドを実行します。

$ rails active_storage:install
$ rails db:migrate

実行するとデータベースにactive_storage_attachments, active_storage_blobs, active_storage_variant_recordsが追加されます。

Userモデルと関連付ける

user.rbに以下の記述を追記します。

app/models/user.rb
 has_one_attached :avatar

コントローラーに追記する

avatarをアップロードできるようにするために以下の記述をregistrations_controller.rbに追記します。

registrations_controller.rb
class RegistrationsController < DeviseTokenAuth::RegistrationsController
    before_action :configure_permitted_parameters

    def update
        super do
          @resource.avatar.attach(account_update_params[:avatar]) if account_update_params[:avatar].present?
        end
    end

    protected
    def configure_permitted_parameters
        devise_parameter_sanitizer.permit(:account_update, keys: %i[avatar])
    end
end

config/routes.rbにも記述を追加します。

config/routes.rb
  mount_devise_token_auth_for "User", at: "auth", controllers: {
    registrations: "api/v1/auth/registrations"
  }
1
0
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
0