2

Does anyone have experience with / can anyone suggest best practices for storing quantities with large variants in magnitude?

For example, an attribute in one of my models is used to store a weight that could be anything from a few micrograms up to a kilogram or more. My assumption is to convert everything to the smallest unit and store it in the database as an integer (since I might lose accuracy with a float?), but it seems weird to be storing kilogram quantities in micrograms..

Is anybody able to suggest a ruby/rails plugin that might help with this kind of behavior, in the more generic sense? In the same way that a 'time' field in a database is converted into a Time object in ruby, how would I go about best intercepting the database entry -> class attribute process, converting a field into my class of choice?

Is there a design pattern for storing varying unit magnitudes that I'm just not thinking of?

Phrogz
  • 296,393
  • 112
  • 651
  • 745
Jeriko
  • 6,547
  • 4
  • 28
  • 40
  • This is a Duplicate of http://stackoverflow.com/questions/5498394/milliseconds-with-rails-and-mysql – Pedro Rolo Apr 03 '11 at 13:57
  • Similar, perhaps, but not a duplicate. When I first searched for answers before posting, your link was not a match; It focuses on time, whereas I'm more interested in a pattern for the general case, which I think Phrogz has answered well. – Jeriko Apr 04 '11 at 08:51
  • As I answered, the pattern for the general case is to use rails aggregations. – Pedro Rolo Apr 04 '11 at 09:30

2 Answers2

3

If precision is important, then what you propose is a good idea. Whether with currency or weights, store the integer amount of the smallest unit you can measure.

Alternatively, use BigDecimal, which provides support for arbitrary precision (as in you-get-to-choose-the-precision, not as in Ruby-randomly-chooses-it). Good support for storing this depends on your database—for example, PostgreSQL provides the NUMERIC data type precisely for this purpose—and requires support from your ORM (presumably ActiveRecord, which supports this in migrations through the :decimal column type).

Even though money typically varies by orders of magnitude smaller than the difference between micrograms to kilograms, you will not run into any problems if you handle this like money and just set your precision appropriately.

Community
  • 1
  • 1
Phrogz
  • 296,393
  • 112
  • 651
  • 745
0

Regarding the Time issue: You don't need a rails plugin for this. You have Rails aggregations for this purpose:

Milliseconds with Rails and Mysql (Is your question an intentional duplicate of this one?!)

As for the precision. That's just a matter of using the best type available in the DBMS.

Community
  • 1
  • 1
Pedro Rolo
  • 28,273
  • 12
  • 60
  • 94