跳到內容 跳到搜尋

Active Record 驗證

Active Record 將大多數驗證都納入 ActiveModel::Validations 中。

在 Active Record 中,所有驗證預設都會在儲存時執行。 Validations 接受 :on 引數,用來定義驗證作用的情境。Active Record 會傳遞 :create:update 的情境,視模型是否是 new_record? 而定。

命名空間
方法
S
V

執行個體的公用方法

save(**options)

傳遞 validate: false 可以略過儲存過程中的驗證。傳遞 context: context 可以變更驗證情境。當驗證模組混入時,這個程式取代了正規的 ActiveRecord::Base#save 方法,驗證模組預設會混入。

# File activerecord/lib/active_record/validations.rb, line 47
def save(**options)
  perform_validations(options) ? super : false
end

save!(**options)

嘗試儲存記錄,就像 ActiveRecord::Base#save 一樣,但如果記錄無效,會產生 ActiveRecord::RecordInvalid 例外,而不是傳回 false

# File activerecord/lib/active_record/validations.rb, line 53
def save!(**options)
  perform_validations(options) ? super : raise_validation_error
end

valid?(context = nil)

執行指定情境下的所有驗證。如果未找到錯誤,傳回 true;否則傳回 false

別名為 validate

如果引數為 false(預設為 nil),當 new_record?true 時,情境設定為 :create;否則設定為 :update。如果引數為情境陣列,post.valid?([:create, :update]),驗證會在多個情境下執行。

沒有 :on 選項的驗證會在任何情境下執行。某些 :on 選項的驗證只會在指定的情境下執行。

其他別名: validate
# File activerecord/lib/active_record/validations.rb, line 69
def valid?(context = nil)
  context ||= default_validation_context
  output = super(context)
  errors.empty? && output
end

validate(context = nil)

別名: valid?