Rails - Scalable calculation model

Posted by H O on Stack Overflow See other posts from Stack Overflow or by H O
Published on 2012-07-04T10:07:38Z Indexed on 2012/07/04 21:16 UTC
Read the original article Hit count: 230

I currently have a calculation structure in my rails app that has models metric, operand and operation_type.

Presently, the metric model has many operands, and can perform calculations based on the operation_type (e.g. sum, multiply, etc.), and each operand is defined as being right or left (i.e. so that if the operation is division, the numerator and denominator can be identified).

Presently, an operand is always an attribute of some model, e.g. @customer.sales.selling_price.sum.

In order to make this scalable, in need to allow an operand to be either an attribute of some kind, or the results of a previous operation, i.e. an operand can be a metric.

I have included a diagram of how my models currently look:

enter image description here

Can anyone assist me with the most elegant way of allowing an operand to be an actual operand, or another metric?

Thanks!

EDIT: It seems based on the only answer so far that perhaps polymorphic associations are the way to go on this, but the answer is so brief I have no idea how they could be used in this way - can anyone elaborate?

EDIT 2: OK, I think I'm getting somewhere - essentially i presently have a metric, which has_many operands, and an operand has_many metrics. I need a polymorphic self join, where a metric can also have many metrics - do I need to call this something else, perhaps calculated_metrics, so that the metric model can use itself? That would leave me with a situation where a metric has_many operands, and a metric has many calculated_metrics.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about database