プロダクト開発日誌

技術のことなど

画像アップロード機能を追加(Active Storage)

ユーザモデルに画像を追加します。

bin/rails active_storage:install

マイグレーションファイルを確認

class CreateActiveStorageTables < ActiveRecord::Migration[5.2]
  def change
    create_table :active_storage_blobs do |t|
      t.string   :key,        null: false
      t.string   :filename,   null: false
      t.string   :content_type
      t.text     :metadata
      t.bigint   :byte_size,  null: false
      t.string   :checksum,   null: false
      t.datetime :created_at, null: false

      t.index [ :key ], unique: true
    end

    create_table :active_storage_attachments do |t|
      t.string     :name,     null: false
      t.references :record,   null: false, polymorphic: true, index: false
      t.references :blob,     null: false

      t.datetime :created_at, null: false

      t.index [ :record_type, :record_id, :name, :blob_id ], name: "index_active_storage_attachments_uniqueness", unique: true
      t.foreign_key :active_storage_blobs, column: :blob_id
    end
  end
end

マイグレーション

bin/rails db:migrate

config/environments/development.rb

# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local

config/storage.yml

# 何処に画像を保存するかの設定

Userモデルに画像を添付できるようにする

class User < ApplicationRecord
  has_one_attached :image
end

User controllerの作成

bin/rails generate devise:controllers users

route.rb

Rails.application.routes.draw do
  devise_for :users, controllers: {
    registrations: 'users/registrations'
  }
  root to: 'areas#index'
  resources :areas
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

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]


  # protected

  # If you have extra params to permit, append them to the sanitizer.
  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:image])
  end

  # If you have extra params to permit, append them to the sanitizer.
  def configure_account_update_params
    devise_parameter_sanitizer.permit(:account_update, keys: [:image])
  end

end

画面の設定

app/views/devise/registrations/new.html.slim app/views/devise/registrations/edit.html.slim

.field
    = f.label :image
    br
    = f.file_field :image