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

ActiveStorageでユーザーアバターの追加

2
Posted at

概要

参考記事を元に使いやすくしたつもりです。
細かい内容は参考記事を確認してください。

環境

Ruby: 2.7.1
Rails: 6.0.2.2

Gem
gem 'image_processing', '~> 1.2'
(Rails6であればデフォルトでGemfileに入っているのでコメントアウトを外す)
gem 'rails-i18n', '~> 6.0'
(国際化(i18n)用。国際化しない場合でも便利)
gem 'mini_magick', '~> 4.10', '>= 4.10.1'
(ActiveStorageの画像を加工して表示できる)

Modelにバリデーションを追加

app/models/user.rb
class User < ApplicationRecord
  # ActiveStorageとUserを紐付け
  has_one_attached :avatar

  # バリデーション
  validate :validate_avatar

  # アバター画像のバリデーション内容
  def validate_avatar
    return unless avatar.attached?
    # 画像サイズの制限
    if avatar.blob.byte_size > 10.megabytes
      # エラーメッセージはi18nから取得
      errors.add(:avatar, :file_too_large)
    elsif !image?
      errors.add(:avatar, :file_type_not_image)
    end
  end

  # 拡張子でファイルの種類を確認
  def image?
    avatar.content_type.in?(%("image/jpeg image/jpg image/png"))
  end
end

エラーメッセージをi18nで追加

rails-i18nを元に、「avatar」、「file_too_large」、「file_type_not_image」を追加

/config/locales/ja.yml
ja:
  activerecord:
    attributes:
      user:
        avatar: "プロフィール写真"
    errors:
      messages:
        record_invalid:       'バリデーションに失敗しました: %{errors}'
        restrict_dependent_destroy:
          has_one:            "%{record}が存在しているので削除できません"
          has_many:           "%{record}が存在しているので削除できません"
        file_too_large:       "はサイズが10メガバイト以内のものを選択してください"
        file_type_not_image:  "はjpg、jpeg、pngのみ選択できます"

画像の表示

こんな感じで表示できる。
variant以下は「mini_magick」による加工。
リサイズと、「strip: true」でEXIF情報を削除。

erb.html
<!-- 存在の確認 -->
<% if @user.avatar.attached? %>
  <!-- 表示 -->
  <%= image_tag @user.avatar.variant(combine_options:{resize:"84x84^",crop:"84x84+0+0",gravity: :center}, strip: true).processed %>
<% end %>

参考

Active Storage移行記:バリデーション編
Railsのactive_storageとmini_magick使ってみる
rails の validation error message の i18n 対応

2
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
2
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?