Ruby / Rails-如何验证小数位数? [英] Ruby/Rails - How can you validate against decimal scale?
问题描述
如何验证小数位数?例如,假设我们要存储小数点后最多2个小数点的酒店的评分。 4.34。 3.76。等等
我在网上阅读了根据您与列相关的精度/比例截断的sqlite。因此,如果您的精度为3,小数位数为2,然后输入1.34567,则将存储1.35。我输入了这个值,尽管我的精度为3,但DB仍以某种方式存储了全部内容。
t.decimal:my_column,precision :3,比例尺:2
所以,如何验证这种情况,为什么呢? postgres会存储大于2的小数位数吗?
小数位数仅在值是字符串时才重要。将其转换为数字后,它具有的小数位数很多,为零或更多。
因此,进行此验证的时间取决于输入(当这是一个字符串,因为用户输入的 all 总是 一个字符串),然后再次在输出上强制正确显示为字符串。在其他所有时间,您都不必担心小数位数。
就Rails而言,您可以使用访问器方法来为您做一些验证:
def my_column =(value)
if value [/\A\d+\.\d\ d\z /]
write_attribute:my_column,值
else
errors.add(:my_column,:invalid)
结束
结束
您不能使用传统的验证器,因为字符串->十进制转换将在验证器运行之前发生。
How you can validate against the scale of a decimal? For example, let's say we want to store ratings for a hotel with maximum 2 decimal points after the decimal. 4.34. 3.76. etc
I've read online that sqlite with truncate based on the precision/scale you've tied to the column. So if you have a precision 3, scale 2, and enter 1.34567 1.35 will be stored.
However, I'm using postgres and this is not the case. I enter this, and the DB stores the full thing somehow despite my precision 3 scale 2.
t.decimal :my_column, precision: 3, scale: 2
So, how do I validate against this kind of thing, and why is postgres storing more than 2 decimal scale to begin with?
The number of decimal places only matters when the value is a string. Once you've converted it to a number, it has however many decimals it has, zero or more.
So, the time to do this validation is on input (when it's a string, as all input from the user is always a string) and then enforce the correct display on output, when it is again a string. At all other times, you should not worry about the number of decimals.
In terms of Rails, you can use an accessor method which does some validation for you:
def my_column=(value)
if value[/\A\d+\.\d\d\z/]
write_attribute :my_column, value
else
errors.add(:my_column, :invalid)
end
end
You can't use a traditional validator as the string->decimal conversion will happen before your validator runs.
这篇关于Ruby / Rails-如何验证小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!