eMgz
eMgz

Reputation: 708

Rails decimal (currency) number not saving when the scale part changes

I have a price field in Rails created as a decimal with precision 8 and scale 2 (or numeric(8,2) in Postgres). When I try to update the scale part, it generates an empty transaction, but I cannot understand why. Any idea on what is going on?

Console outputs:

irb(main):051:0> puts o.price
8.0
=> nil

irb(main):052:0> o.price = "8,22"
=> "8,22"

irb(main):053:0> puts o.price
8.22
=> nil

irb(main):054:0> o.save
   (0.5ms)  BEGIN
   (0.4ms)  COMMIT
=> true

irb(main):055:0> o.reload; puts o.price    
8.0
=> nil

EDIT: Updating the whole number works normally, the problem only appears when updating the scale part:

irb(main):017:0* puts o.price
8.0
=> nil

irb(main):018:0> o.price = "9,22"
=> "9,22"

irb(main):019:0> o.save
   (0.4ms)  BEGIN
   (0.9ms)  UPDATE "order_items" SET "price" = 9.22, "updated_at" = '2014-01-10 20:17:31.753908' WHERE "order_items"."id" = 1469
   (22.1ms)  COMMIT
=> true

irb(main):020:0> o.reload; puts o.price
9.22
=> nil

EDIT 2: Also tested with others decimals ( 8,22 => 8,44) and it works. The problem occurs when the price is rounded to 0 ( 8,00 => 8,22 doesn't update)

Upvotes: 2

Views: 1364

Answers (2)

eMgz
eMgz

Reputation: 708

Turns out it was a bug in the delocalize gem. Upgrading it from 0.3.1 to 0.3.2 solved the problem. Issue:

https://github.com/clemens/delocalize/issues/57

Upvotes: 1

BroiSatse
BroiSatse

Reputation: 44715

When you do:

o.price = "8,22"

You assign string object, not decimal value. Since you are using coma as a separator '8,22'.to_f returns 8.0.

Try assigning a number instead.

o.price = 8.22 

Upvotes: 1

Related Questions