1
1

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 5 years have passed since last update.

Rails Active Storageを使って画像のアップロード機能を実装する

1
Posted at

Active Storageによる画像アップロード機能の実装

作業内容

  1. 画像変換ツールをインストール
  2. Active Storageをインストール
  3. userモデルにActive Storageの設定を追記

● ImageMagickのインストール
ImageMagickは、コマンドラインから簡単に画像の保存形式の変更などが出来るツールである。
ターミナルで下記のコマンドを実行。

$ brew install imagemagick

ImageMagickがインストールできたら、mini_magickをインストールする。
gemifileに追記。

gemfile
gem 'mini_magick'

追記したらbunle install

$ bundle install

● Active Storageのインストール

$ rails active_storage:install
$ rake db:migrate

上記のコマンドを実行すると、Active Storageが使用するテーブル用のマイグレーションファイルが作成される。
その後続けて必ずマイグレートすること。

● User.rbに追記
下記の追記をすることで、ユーザーのレコードを画像を紐づけることができる。ユーザーテーブルにカラムを追加する必要がなくなる。とても便利!

user.rb
class User < ApplicationRecord
  #Include default devise modules. Others available are:
  #:confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_one_attached :avatar  # 追記

●/devise/registraions/new.html.erbの編集(例)

/devise/registrations/new.html.erb
       # 省略
  <div class="label"><%= f.label :nickname %><br />
  <%= f.text_field :nickname %></div>
  <div class="field">
  <%= f.file_field :avatar %>
  </div>
       # 省略

has_one_attached :avatarと記述するだけでテーブルにカラムを追加しないでできてしまう。

  • ストロングパラメータを追加することを忘れずに⭐️
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?