2012-04-26 157 views
0

我試圖創建一個驗證,如果當前對象country_code設置爲ES,強制:phone字段爲9位長。驗證ActiveRecord屬性長度deppending在其他對象屬性

我試圖做這樣的事情,但它不起作用。

validates_length_of :phone, :is => 9, :message => "number needs to be at least 9 digits." if self.country_code == "ES" 

回答

2

我知道你在尋找的是:

validates_length_of :phone, :is => 9, 
:message => "number needs to be at least 9 digits.", 
:if => "country_code == 'ES'" 

或者

validates_length_of :phone, :is => 9, 
:message => "number needs to be at least 9 digits.", 
:if => Proc.new { |a| a.country_code == 'ES' } 

看看該文檔here