[英]How do you validate numbers with Ruby On Rails using % operator
我想確保進入此對象的數字可被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...
您可以為此編寫自己的簡單驗證方法,如下所示:
validate :divisible_by_three
def divisible_by_three
unless attribute%3 == 0
self.errors.add(:attribute, "is not divisible by 3")
end
end
我不認為任何內置的rails方法,所以這可能是最好的解決方案。
湯姆
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.