2012-07-06 57 views

回答

3

試試這個:

# your_model.rb 
validate :only_valid_numbers 

private 

    def only_valid_numbers 
     if (self.number % 3) != 0 
      self.errors[:base] << "Number must be divisible by 3!" 
     end 
    end 

記住0 % 3將是0,所以如果你不想允許,改變if語句:

if self.number != 0 and ...etc... 
0

您可以編寫自己的簡單的驗證方法如下:

validate :divisible_by_three 

def divisible_by_three 
    unless attribute%3 == 0 
    self.errors.add(:attribute, "is not divisible by 3") 
    end 
end 

我不認爲任何內置的rails方法所以這可能是最好的解決方案。

Tom