使用选项

:on 选项允许你指定验证何时发生。所有内置验证助手的默认行为都是在保存时运行的(无论是在创建新记录时还是在更新时)。

class Person < ApplicationRecord
  # it will be possible to update email with a duplicated value
  validates :email, uniqueness: true, on: :create
 
  # it will be possible to create the record with a non-numerical age
  validates :age, numericality: true, on: :update
 
  # the default (validates on both create and update)
  validates :name, presence: true
end