miko
miko

Reputation: 11

How can I give validation on decimal field in Rails?

I have Order model, which has a decimal :total. I want to validate that this total is two decimal places, greater than 0, and is less than a million.

validates :total, presence: true, format: { with: /\A\d+(?:\.\d{0,2})?\z/ }, numericality: { greater_than: 0, less_than: 100_000_000 }

When my total becomes 1234567890.00, it raises an error:

PG::NumericValueOutOfRange: ERROR: numeric field overflow DETAIL: A field with precision 11, scale 2 must round to an absolute value less than 10^9. : UPDATE "orders" SET "tax_total" = $1, "total" = $2, "updated_at" = $3 WHERE "orders"."id" = $4

I also tried to add this migration:

def self.up
  change_column :orders, :total, :decimal, :precision => 11, :scale =>2
end

in my model, but the error is still there.

I want validation message here.

Upvotes: 0

Views: 2340

Answers (1)

Neeraj
Neeraj

Reputation: 21

For 1234567890.00 to fit in, your migration should be

def self.up
    change_column :orders, :total, :decimal, :precision => 12, :scale =>2
end

For validating numericality of number use the following at the rails level:

validates_numericality_of :decimal, less_than_or_equal_to: BigDecimal(10**8)

Remember, precision is the total number - (mantissa + characteristic) For your case 1234567890 add up to 10. Add 2 for decimal to this and that's how your precision should be 12 rather than 11.

Upvotes: 2

Related Questions