开发者

Dealing with precise units in Rails 3

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 pat开发者_运维问答tern for storing varying unit magnitudes that I'm just not thinking of?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜