Suppose in my rails application I have a model Entry, which has a nested model Measures, such that each entry has_many measures (and measures belongs_to entry).
Each measure has its own incentive. Is it possible that Entry has an integer also named incentive, whose value is equal to the sum of all of its measures? How do you achieve this?
To me, it seems like this kind of becomes a two part question:
How to make a models field, upon submission, be defined based on another fields value? Then.. How to make a value, upon submission, be defined based on its nested models values?
Try implement a callback using
after_updatein the model of the nested attributes, which updates its parent:You might need to use the same method on the
after_createcallback as well.EDIT:
After having read about
touchin another question, I’d like to update my approach:What happens here, is that everytime a Measure is created or edited, it informs its Entry that it is updated by calling its touch method. In the entry, we may use the callback
after_touchin order to recalculate the sum of the measures. Note that theafter_touch-callback is called on creation, deletion and modification of the measures.Compared to my previous approach, this approach puts the responsability on the Entry-objects, which is favourable from a design point-of-view.