title: Lazy setting of model attributes in Rails?
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>I have tried to this:</p>
  
  <pre><code>def profit
    if not self[:profit]
      update_attribute :profit, expensive_computation
    end
    self[:profit]
  end
  </code></pre>
  
  <p>Unfortunately, that only gets half the job done. The computed value gets stored, but every time I call profit, it computes the value again.</p>
  
  <p>UPDATE:</p>
  
  <p>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:</p>
  
  <pre><code>def profit
    unless read_attribute(:profit)
      update_attribute(:profit, expensive_computation ) 
      self.save!
    end
    read_attribute(:profit)
  end
  </code></pre>