Rails - Caching total sum of receipts in a budgeting app - best practice
Context: budget tracking app which will have lots of receipts belonging directly to a user.
One of many calculations I will have to keep is a running total of all receipts entered since day 1. As time goes on and receipts increase this will take longer to calculate and perhaps become a bottleneck. And this will be called frequently - every time a user adds a new receipt, edits an old one etc.
So Im wondering how do i avoid this constant summing. Perhaps i should somehow section fence receipts into monthly folders, each folder keeping a track of its subtotal. So if add a new receipt to any month only the sum is calculated for those receipts. Is this the right approach and how should it be implemented? Should i be creating a months model here?
Im not great a db design and was hoping someone maybe able to comment on this approach or开发者_如何学编程 offer a cleaner way.
Take a look at counter_cache in active record. This sounds like a classic example.
On the User model, you'll add a 'receipts_count' column.
add_column :users, :receipts_count, :integer, :default => 0, :null => false
And on the Receipts model, you'll add
belongs_to :user, :counter_cache => true
You'll want to also look into how to set that number initially. You can do this with a rake task or in the migration. This has some gotchas, as you'll see. Counter caches are read-only and to update them in a migration, you'll need to set the value through and ActiveRecord::Base.connection.execute("...") command
There's lots of discussion on this on the web, railscasts, etc., and there's way's to add a custom counter if you want, you'll want to read more on it than I can add here.
精彩评论