blue workbench

Ruby and Rails

【Rails】バリデーションまとめ

# frozen_string_literal: true

class User < ApplicationRecord
  validates :screen_name,
            # 必須
            presence: true,
            # 長さ
            length: { maximum: 20 },
            # 一意制約(大文字小文字区別しない)
            uniqueness: { case_sensitive: false }
end
# frozen_string_literal: true

class Product < ApplicationRecord
  # 必須
  validates :name,
            :price,
            presence: true

  # 数値(しかも整数のみOK)
  validates :price, numericality: { only_integer: true }
end

参考

railsguides.jp