0
0

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 1 year has passed since last update.

【Ruby on Rails】Active Storageの導入方法

Last updated at Posted at 2022-11-15

Active Storageの導入方法

ImageMagick:
画像の作成やサイズ変更、保存形式の変更ができる。Gemではなく、ソフトウェア。
MiniMagick:
ImageMagickの機能をRubyで扱えるようにしてくれるGem。
ImageProcessing:
MiniMagickでは提供できない、画像サイズを調整する機能を提供するGem。

Active Storageを使用する為に必要なツールのインストール

ImageMagickのインストール

ターミナル
brew install imagemagick

MiniMagickとImageProcessingのインストール

Gemfile最終行に以下を追記

Gemfile
gem 'mini_magick'
gem 'image_processing', '~> 1.2'
ターミナル
bundle install

以上でActive Storageを使用する為に必要なツールのインストールは完了。

Active Storageをアプリケーション内で使用する準備

Active Storageをインストール

ターミナル
rails active_storage:install
ターミナル
rails db:migrate

Active Storageのテーブルに、画像を保存するための実装

モデルと画像ファイルを紐付ける。
この設定によって「モデル.image」が画像ファイルを示すことになる。

app/models/モデル.rb
class モデル < ApplicationRecord
  has_one_attached :image
end

permitに:imageキーを追加することで、imageという名前で送られてきた画像ファイルの保存を許可する。

app/controllers/モデルs_controller.rb
class モデル < ApplicationRecord

private

def モデル_params
    params.require(:モデル).permit(:カラム名1, :image).merge(user_id: current_user.id)
end

#techcamp136期

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?