title: rails override default getter for a relationship (belongs_to)
body: <p>So I know how to override the default getters for attributes of an ActiveRecord object using</p>
  
  <pre><code>def custom_getter
    return self[:custom_getter] || some_default_value
  end
  </code></pre>
  
  <p>I'm trying to achieve the same thing however for a belongs to association.  For instance.</p>
  
  <pre><code>class Foo &lt; AR
    belongs_to :bar
  
    def bar
      return self[:bar] || Bar.last
    end
  end
  
  class Bar &lt; AR
    has_one :foo
  end
  </code></pre>
  
  <p>When I say:</p>
  
  <pre><code>f = Foo.last
  </code></pre>
  
  <p>I'd like to have the method <code>f.bar</code> return the last Bar, rather than nil if that association doesn't exist yet.</p>
  
  <p>This doesn't work however.  The reason is that self[:bar] is always undefined.  It's actually self[:bar_id].</p>
  
  <p>I can do something naive like:</p>
  
  <pre><code>def bar
    if self[:bar_id]
      return Bar.find(self[:bar_id])
    else
      return Bar.last
    end
  end
  </code></pre>
  
  <p>However this will always make a db call, even if Bar has already been fetched, which is certainly not ideal.</p>
  
  <p>Does anyone have an insight as to how I might have a relationship such that the belongs_to attribute is only loaded once and has a default value if not set.</p>