1
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.

ActiveStorageで画像を扱う際のTips

Posted at

画像を加工して表示する

variantメソッドを使用する。下記は横幅を512pxにする例。
縦のサイズを指定する場合は、"512x256"などのように"横x縦"で指定する


class Post < ApplicationRecord
  has_many_attached :photos do |attachable|
    # 512にリサイズする。:resizedという名前でアクセスできる
    attachable.variant(:resized, resize: "512")
  end
  ...

  # リサイズした画像のURLを返す。
  def photo_urls
    photos.map { |photo| url_for(photo.variant(:resized).processed) }
  end
end

画像アクセスに有効期限を設ける

  • application.rbに以下のように記述
# 1時間でアクセスが無効になる
config.active_storage.urls_expire_in = 1.hour

S3にアップロードする

  • storage.ymlに設定を記載
amazon:
  service: S3
  access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
  secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
  region: <%= Rails.application.credentials.dig(:aws, :region) %>
  bucket: <%= Rails.application.credentials.dig(:aws, :s3_bucket) %>
  • production.rb(またはapplication.rb)で使用するActiveStorageのサービスを変更
  # Store uploaded files on the local file system (see config/storage.yml for options).
  config.active_storage.service = :amazon
  • AWSへのアクセスキー等はcredentialで設定
EDITOR=vi RAILS_ENV=production ./bin/rails credentials:edit
aws:
  access_key_id: ...
  secret_access_key: ...
  region: ap-northeast-1
  s3_bucket: images
1
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
1
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?