您還可以創建方法來驗證模型的狀態,並在錯誤集合無效時將消息添加到錯誤集合中。然後您必須使用驗證(API)類方法註冊這些方法,並傳入驗證方法名稱的符號。
您可以爲每個類方法傳遞多個符號,並且相應的驗證將按照與它們註冊相同的順序運行。
有效嗎?方法將驗證錯誤集合是空的,所以當你想驗證失敗自定義的驗證方法應補充錯誤吧:
class Invoice < ApplicationRecord
validate :expiration_date_cannot_be_in_the_past,
:discount_cannot_be_greater_than_total_value
def expiration_date_cannot_be_in_the_past
if expiration_date.present? && expiration_date < Date.today
errors.add(:expiration_date, "can't be in the past")
end
end
def discount_cannot_be_greater_than_total_value
if discount > total_value
errors.add(:discount, "can't be greater than total value")
end
end
end
默認情況下,這樣的驗證將運行每次調用有效時間?或保存對象。但是也可以通過給validate方法的on選項來控制何時運行這些自定義驗證,可以使用::create或:update。
class Invoice < ApplicationRecord
validate :active_customer, on: :create
def active_customer
errors.add(:customer_id, "is not active") unless customer.active?
end
end