25
10

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 3 years have passed since last update.

Rails | バリデーション validates と validate の違い

Last updated at Posted at 2021-09-09

モデル(model)にバリデーションを書く際に使い分けすることがあったのでメモ。

それぞれの違いについて

###validates
標準のバリデーションを書くときはこれ

使い方はRailsガイドを参照
https://railsguides.jp/active_record_validations.html

###validate
自分でオリジナルのバリデーション用メソッドを書くときはこれ

validateの使用例

model
validate :photo_size, :photo_length

private
  def photo_size
    photos.each do |photo|
      if photo.blob.byte_size > 5.megabytes
      photo.purge
      errors.add(:photos, "は1つのファイル5MB以内にしてください")
      end
    end
  end

  def photo_length
    if photos.length > 10
      photos.purge
      errors.add(:photos, "は10枚以内にしてください")
    end
  end

私はActiveStorageでバリデーションを作成した際に違いに気づき、疑問に思ったので残しておきます。

25
10
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
25
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?