LoginSignup
7
9

More than 3 years have passed since last update.

【Rails】Active Storageで拡張子のvalidateを作成する時の注意点

Posted at

はじめに

タイトル通りActive Storageで拡張子に関するvalidateを作成したところ、Userがサインアップする時にエラーが出てしまった。

事象

Userモデルに以下のような感じで、Active Storageでアップロードするimageに対して拡張子を指定するvalidateを作成した。

user.rb
class User < ApplicationRecord
  has_one_attached :image

  validate :image_content_type

  def image_content_type
    extension = ['image/png', 'image/jpg', 'image/jpeg']
    errors.add(:image, "の拡張子が間違っています") unless image.content_type.in?(extension)
  end

ところがこの後、userを新規アカウント登録させようとすると以下のエラーが出てしまった。

content_type delegated to attachment, but attachment is nil

スクリーンショット 2019-07-11 19.40.04.png

原因

今回の場合はUserをcreateする時にemailとpasswordしかpostしないので、
当然imageはparamsに乗らないため、image.attached?falseになります。
上記のエラーはimageがattachedされてないのにcontent_typeを呼び出したことによるエラーっぽいです。

解決方法

image.attached?falseの時はvalidateしないようにすれば解決なので、

user.rb
class User < ApplicationRecord
  has_one_attached :image

  validate :image_content_type, if: :was_attached?

  def image_content_type
    extension = ['image/png', 'image/jpg', 'image/jpeg']
    errors.add(:image, "の拡張子が間違っています") unless image.content_type.in?(extension)
  end

  def was_attached?
    self.image.attached?
  end

これで無事Userがcreate出来るようになりました。

7
9
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
7
9