2012-05-28 70 views
0

我有這個自定義驗證,拋出一個「未定義的方法`>'爲零:NilClass」當生日沒有設置,因爲生日是零。ROR如何最好地處理零自定義驗證

validate :is_21_or_older 
def is_21_or_older 
    if birthday > 21.years.ago.to_date 
    errors.add(:birthday, "Must 21 Or Older") 
    end 
end 

我已經validates_presence_of生日所以是有一個validates_presence_of經過後只叫is_21_or_older方式嗎?

回答

3

Rails獨立運行所有驗證器,以便一次給出所有錯誤的數組。這是爲了避免所有常見的情況:

請輸入密碼。

pass

你輸入的密碼是無效的:它不含有一個數字。

1234

你輸入的密碼是無效的:它不包含一個字母。

a1234

你輸入的密碼是無效的:它不長至少六個字符。

ab1234

你輸入的密碼是無效的:你不能在一個序列中使用三個或多個連續字符。

piss off

你輸入的密碼是無效的:它不含有一個數字。

有兩件事你可以做,我知道。要麼包括您的自定義驗證器下的所有內容,在這種情況下,所有內容都在您的控制之下,或者使用:unless => Proc.new { |x| x.birthday.nil? }修飾符來明確限制您的驗證器在其中斷的情況下運行。我肯定會建議第一種方法;第二是哈克。

def is_21_or_older 
    if birthday.blank? 
    errors.add(:birthday, "Must have birthday") 
    elsif birthday > 21.years.ago.to_date 
    errors.add(:birthday, "Must 21 Or Older") 
    end 
end 

也許一個更好的方法是保持存在驗證,只是退出自定義驗證時,看到對方驗證的條件失敗。

def is_21_or_older 
    return true if birthday.blank? # let the other validator handle it 

    if birthday > 21.years.ago.to_date 
    errors.add(:birthday, "Must 21 Or Older") 
    end 
end