Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #7402 (closed enhancement: untested)

Opened 2 years ago

Last modified 2 years ago

[PATCH] decimal columns propagates scale into BigDecimal values

Reported by: ricardo Assigned to: core
Priority: normal Milestone: 1.x
Component: ActiveRecord Version: edge
Severity: normal Keywords: BigDecimal decimal scale
Cc:

Description

decimal(x,y) columns in Rails 1.2 are mapped to BigDecimal object. They works well, but it could be better.

For example, one column:

price decimal(5,2)

for an "articles" table is mapped to a BigDecimal object, but that object doesn't "remember" the corresponding column's :scale.

Therefore,

article = Articles.find(1) article.price # this object is a BigDecimal one, but it doesn't knows how many fractional digits must contain

So "article.price.to_s" will not "render" the correct fractional digits based of the column's scale.

For example, if we save the 5.20 value into the column, then the expression "article.price.to_s" will return "5.2".

In that way, if we save the 5 value, the expression "article.price.to_s" will return "5.0".

If the BigDecimal object could "remember" how many decimals it must to show, then the to_s method could always give you more appropriate results. In the case of 5.20, to_s will returns "5.20"; in the case of 5, to_s will returns "5.00". In the same way, if the column were decimal(5), when you save 5.20 or 5 values, to_s will always returns "5".

The patch I developed tries to solves the problem. With this patch, a BigDecimal object have a scale attribute, so the to_s method can know how to print the decimal correctly.

The patch touches files from ActiveRecord and ActiveSupport. The ActiveRecord part puts the scale into the BigDecimal object, and the ActiveSupport part prints the BigDecimal object according to the scale within in.

Attachments

bigdecimals_with_scale.diff (3.3 kB) - added by ricardo on 01/26/07 20:32:29.

Change History

01/26/07 20:32:29 changed by ricardo

  • attachment bigdecimals_with_scale.diff added.

01/28/07 09:51:30 changed by bitsweat

  • status changed from new to closed.
  • resolution set to untested.

Interesting idea, ricardo. However, the meaning of the scale returned by the adapter varies across databases, splitting the _original_to_s result on a period doesn't account for other locales, scale should be set by the adapter rather than AR::Base#read_attribute_before_type_cast, and there are no unit tests.

01/28/07 22:44:01 changed by ricardo

Yes, I know the solution is not the best possible. I'm a Rails newbie (and a Ruby newbie) and I haven't the necessary knowledge to do what I want. I don't know if this is the best forum to do the call, but I would like to see this idea implemented by someone with the necessary knowledge. Of course, I'm ready to help (assuming I'm not a Rails expert).

What can be do?