I have a model which is generated by parsing a data file. There are several interesting values which are not present in the original data file but can be derived from the ones that are.
However, many of these derived values are expensive to compute, so I would like to store them in the database once they have been computed.
I have tried to this:
def profit
if not self[:profit]
update_attribute :profit, expensive_computation
end
self[:profit]
end
Unfortunately, that only gets half the job done. The computed value gets stored, but every time I call profit, it computes the value again.
UPDATE:
Turns out the problem was not in the method, but in a find_by_sql statement earlier on that had Rails confused about the id's of the models. The code I ended up with was this:
def profit
unless read_attribute(:profit)
update_attribute(:profit, expensive_computation )
self.save!
end
read_attribute(:profit)
end