Ruby/Rails - How can you validate against decimal scale?

烈酒焚心 提交于 2019-12-10 07:57:52

问题


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?


回答1:


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.




回答2:


A simple approach would be to multiply the rating by 100 and store it as an integer. Then your validation should be trivial.



来源:https://stackoverflow.com/questions/24098990/ruby-rails-how-can-you-validate-against-decimal-scale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!