[英]How do you validate numbers with Ruby On Rails using % operator
I want to make sure that numbers coming into this object are divisible by 3. How do I use the validate on the model to prevent invalid input? 我想确保进入此对象的数字可被3整除。如何在模型上使用验证来防止无效输入?
Thanks! 谢谢!
Try this: 尝试这个:
# 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
Remember that 0 % 3
will be 0, so if you don't want to allow that, change the if statement to: 请记住,
0 % 3
将为0,因此如果您不想允许,请将if语句更改为:
if self.number != 0 and ...etc...
You can write your own simple validation method for this like so: 您可以为此编写自己的简单验证方法,如下所示:
validate :divisible_by_three
def divisible_by_three
unless attribute%3 == 0
self.errors.add(:attribute, "is not divisible by 3")
end
end
I don't think any of the built in rails methods so this is probably the best solution. 我不认为任何内置的rails方法,所以这可能是最好的解决方案。
Tom 汤姆
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.