How to use Decimal with precision and scaling?

Using rails 3.0.3, I migrated the decimal column on my base using the following migration:

  change_table :products do |t| t.change :price, :decimal, :precision => 10, :scale => 2 # other code end 

Migration works fine, but I can still save the value, for example 4.64564, where it should only store 4.65

Also, apart from the migration file I created, schema.rb does not contain scale / precision information.

Why do rails accept precision / scale transfers to ignore it?

+6
source share
2 answers

I had the same problem, please look at lib: https://github.com/dmgr/dmg_decimal

With it, you can use it in such a model:

 def price= val self[:price] = Dmg::Decimal.real(val, scale: 2, precision: 10).to_d if val.present? end 
+1
source

You should try

 change_column :products, :price, :decimal, :precision => 10, :scale => 2 
+1
source

Source: https://habr.com/ru/post/905004/


All Articles