hellion
hellion

Reputation: 4830

rails sums model

I have a lot of sum functions in my app. I am moving all data sums to a separate model...lets call it...sums. This will make calling those numbers faster as I wont nail the database everytime I need to sum many rows.

What I would like to do is update the sum row (many attributes) each time certain other models are created or updated. I am trying to this via each model using a class method but for some reason its not working.

Im wondering where I can create a universal method that can be called from an after_create callback for whichever models I choose. The sum is associated to an account, which is not the model being updated. Other account associated models are the ones that will hit the sums model. Therefor, I will probably need to pass self.account_id to the callback method.

Like Papertrails versions model, that is updated everytime another model is saved.

Upvotes: 0

Views: 70

Answers (1)

Srikanth Venugopalan
Srikanth Venugopalan

Reputation: 9049

Have a look at Statistics gem.

It has a cache option that uses Rails cache to prevent repeated aggregation calls to database.

I would prefer something like this as opposed to have an update every time a property gets updated. If you are not planning to hold the sums model in memory, then you will have to fire as many updates to sums table as there are actual updates.

While it may be OK to have write-time overheads, as opposed to read-time, Statistics comes with other options to optimize.

Upvotes: 1

Related Questions