2017-03-07 120 views
0

我試試gem validates_operator。 我需要定製我的消息此驗證:Validates_overlap自定義消息?

驗證:arrival_date,:DEPARTURE_DATE出發,重疊:{
範圍: 「place_id」,
MESSAGE_TITLE: 「錯誤」,
MESSAGE_CONTENT:「不可能預訂這個地方這個日期」}

,但我有簡單形式的默認消息:‘請查看以下’

THX針對存在的問題未來的答案。

回答

0

您還可以創建方法來驗證模型的狀態,並在錯誤集合無效時將消息添加到錯誤集合中。然後您必須使用驗證(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