LoginSignup
0
0

【Rails】ActiveStorageにバリデーションを設定する方法

Posted at

Gemをインストールする

active_storage_validationsをインストールします。

Gemfile
gem 'active_storage_validations'

# :dimension または :aspect_ratioを使用する場合には以下のいずれかを併せてインストールします。
gem 'mini_magick', '>= 4.9.5'
gem 'ruby-vips', '>= 2.1.0'

ターミナル
bundle install 

バリデーションを設定する

モデルにバリデーションを記述します。

app/models/user.rb
class User < ApplicationRecord
  has_one_attached :avatar

  validates :avatar, content_type: { in: %w[image/jpeg image/png] }, size: { less_than_or_equal_to: 2.megabytes }
end

上記の場合にはjpegおよびpngのファイルで2MB以下のものを許可します。

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