LoginSignup
0

More than 5 years have passed since last update.

【Rails】ActiveStorage で一番コンパクトな画像添付の実装手順まとめ

Last updated at Posted at 2018-10-15

Active Storage を始めるにあたって、一番コンパクトな実装、

  • Productモデルに対して画像を1つ添付できる
  • 画像をローカルで保存する

のステップをまとめまています。

大まかな手順

  1. ActiveStorageをインストールする
  2. storage.yml の作成
  3. 環境設定
  4. モデルにファイルを添付
  5. コントローラ(create,updateはデフォルトでOK)
  6. ビューに表示

ActiveStorageをインストールする

テーブルを作成
$ rails active_storage:install
$ rails db:migrate
  • active_storage_blobsactive_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
    画像がありません

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