Active Storage を始めるにあたって、一番コンパクトな実装、
- Productモデルに対して画像を1つ添付できる
- 画像をローカルで保存する
のステップをまとめまています。
大まかな手順
- ActiveStorageをインストールする
-
storage.yml
の作成 - 環境設定
- モデルにファイルを添付
- コントローラ(create,updateはデフォルトでOK)
- ビューに表示
ActiveStorageをインストールする
テーブルを作成
$ rails active_storage:install
$ rails db:migrate
-
active_storage_blobs
とactive_storage_attachments
という名前の2つのテーブルがつくられます。
storage.yml
の作成
config/storage.yml
local:
service: Disk
root: <%= Rails.root.join("storage") %>
環境設定
config/environments/development.rb
config.active_storage.service = :local
モデルにファイルを添付
app/models/product.rb
# 単数の場合
class Product < ApplicationRecord
has_one_attached :image
end
コントローラ
-
#create
,#update
アクションはデフォルトでOK
app/controllers/products_controller.rb
def destroy
# アタッチされていれば削除
@product.image.purge if @product.image.attached?
@product.destroy
respond_to do |format|
format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def product_params
params.require(:product).permit(:name, :price, :image, :description)
end
ビューに表示
app/views/products/show.html.haml
%p
- if @product.image.attached?
=image_tag url_for(@product.image), style: "width: 20rem;"
- else
画像がありません