I have a model "Wrapper", which has_many of another model "Category", which in turn has_many of another model, "Thing".
"Thing" has the integer attributes :count and :number. It also has an instance method defined as such in models/thing.rb:
def ratio
(self.count + self.number).to_f / Thing.all.count.to_f
end
"Category", then, has this instance method, defined in models/category.rb:
def thing_ratios
self.things.sum(&:ratio.to_f)
end
Finally, my wrapper.html.erb view shows Categories, listed in order of thing_ratios:
<%= @wrapper.categories.all.order(&:thing_ratios).each do |category| %>
...
My question is this: every time someone reloads the page wrapper.html.erb, would every single relavant calculation have to be recalculated, all the way down to self.count for every Thing associated with every Category on the page?
In addition to the resources that @Kelseydh provided, you can also consider memoization for when you hit the same function multiple times as part of the same request. However, it will not retain its value after the request is processed.
Yes it will be recalculated every time. If this is an expensive operation you should add a counter_cache (guide: http://railscasts.com/episodes/23-counter-cache-column) for the count and look into caching the query result using a service like memcache.
Many caching strategies exist, but for the database/Rails app itself Russian doll caching is considered the most flexible approach. If your data doesn't update often (meaning you don't need to worry about cache expiration often) you may be able to get way with page caching -- if so, count yourself lucky.
Some resources to get you started:
DHH on Russian Doll Caching: https://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works).
Railscast on cache keys: http://railscasts.com/episodes/387-cache-digests
Advanced caching guide: http://hawkins.io/2012/07/advanced_caching_revised/
Not free, but I found this series was what really let me understand various forms of caching correctly: http://www.pluralsight.com/courses/rails-4-1-performance-fundamentals
来源:https://stackoverflow.com/questions/28492404/is-every-relavant-calculation-performed-every-time-the-page-is-loaded