I’m working on a Rails 3 app that requires a few fields that can be given in multiple units of measure, e.g. miles, kilometers, etc. for distances, miles-per-hour, meters-per-second, etc. for speeds, and so on. I’m curious how others have modeled these types of compound datatypes in Rails. Some requirements that make it interesting:
the original value and unit as entered by the user should be saved for each field value
I have multiple fields on one object that have units associated with them
I need to be able to total/average/min/max fields independent of their individual units (e.g. in metric)
I considered creating a separate UnitValue class (with value, unit, and metric fields) and referencing instances of this class from my main class, but it doesn’t seem to quite fit. The most logical association would be a “has_one” on the main object, but this would require me to add a “belongs_to” for each use of the UnitValue class elsewhere in my models, which is ugly. I could also flip the 1-to-1 association around, but using “belongs_to” on the main object doesn’t seem quite right, either, and I’d still need multiple “has_one” associations on the UnitValue class, even though this wouldn’t require separate database columns.
What I’d really like is to have my UnitValue object flattened/embedded into the main object table as multiple fields, but I’m not sure if that’s possible in Rails at all. Anyone have any advice on the right direction to take here?