Harry
Harry

Reputation: 4835

Rails - Self referencing model?

I currently have a metric model, that can take two operands and perform a calculation based on its operation_type, producing a result through the custom result method. This is working as expected.

In order to make this scalable, I would like to be able to use two operands (as currently), one operand and one metric, or two metrics to perform the calculation. The reason for this is that it is then scalable - I can use the results of previous operations.

Where I am stuck is how to create this self join - I imagine that I need to go down the road of a polymorphic self reference somehow, but the documentation is not leading me to the answer. I have currently got a setup with a calculated_metric model in addition, but i'm not sure if this is the way to go.

My models look as follows:

class Metric < ActiveRecord::Base
    attr_accessible :name, :operation_type_id
end

class Operand < ActiveRecord::Base
    attr_accessible :object, :attribute
end

class Calculated_metric < ActiveRecord::Base
    attr_accessible :metric_id, :calculated_metric_id
end

Any assistance would be greatly appreciated. Thanks!

EDIT: Perhaps I can clarify this a little: I currently have a separate calculated_metric model; is this the best approach to take in order to use the results of another metric in my calculation, or could I achieve this more simply by adding a left_metric and right_metric to my existing metric table (left and right are so that if the equation is a subtraction, for example, it knows which one is being taken away)? I'm not sure if this is an ideal solution, as they will be null in a large number of cases.

Upvotes: 0

Views: 482

Answers (1)

Harry
Harry

Reputation: 4835

I believe I may have stumbled upon a possible here - rather than having the metric reference itself, I have added a metric_id column to the operand model, which means that it can refer to an object attribute or to another metric.

I think this solution works, albeit that there will always be at least one null column in the operand model; as such, better solutions are still welcome.

Thanks!

Upvotes: 1

Related Questions