chris P
chris P

Reputation: 6599

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

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?

Upvotes: 4

Views: 2352

Answers (2)

user229044
user229044

Reputation: 239501

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.

Upvotes: 2

Hew Wolff
Hew Wolff

Reputation: 1509

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

Upvotes: 0

Related Questions