Syl
Syl

Reputation: 3829

How to use Decimal with precision and scale?

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

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

The migration works ok, but I can still store value like 4.64564 where it should only store 4.65

On top of that, except in the migration file I created, schema.rb does not contain info about scale/precision.

Why does rails accept precision/scale migration to ignore it?

Upvotes: 7

Views: 7722

Answers (2)

BooVeMan
BooVeMan

Reputation: 363

You should try with

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

Upvotes: 3

Dawid Grzesiak
Dawid Grzesiak

Reputation: 402

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

With it you can use it in a model like that:

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

Upvotes: 1

Related Questions