I have two models:
Program < ActiveRecord::Base
has_many :events
def federal_financing
events.sum(&:federal_financing)
end
def regional_financing
events.sum(&:regional_financing)
end
def local_financing
events.sum(&:local_financing)
end
end
Event < ActiveRecord::Base
belongs_to :program
# events table have this decimal fields: federal_financing, local_financing, regional_financing
end
Always if I call one of these three methods I'm calling another ones. So I want to avoid of loading events each time I call any of these methods. Current solution now is to define
def after_initialize
@all_events = events
end
and use @all_events instead of events in methods. BUT I do not want to load events when object loads - I want "cache" events only if any of these three methods was called and other methods should use cached version of events.