11
19

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.

Active Storage validation設定方法

Posted at

ユーザー登録の際に、アバター画像添付を必須としたい場合のvalidationを学んだ備忘録

user.rb
  has_one_attached :image
  validate :image_presence

  def image_presence
    if image.attached?
      if !image.content_type.in?(%('image/jpeg image/png'))
        errors.add(:image, 'にはjpegまたはpngファイルを添付してください')
      end
    else
      errors.add(:image, 'ファイルを添付してください')
    end
  end

画像が添付されていたら、それがjpegまたはpngファイルであるか確認、
画像が添付されていなかったらファイル添付を促すように実装しています。

参考

ActiveStorageとバリデーションエラーの挙動

11
19
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
11
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?