title: How to get most recent single item from many with ActiveRecord associations?
body: <p>I'm having some issues with my code. This is probably due to some design fault. I've tried several things. Here are two.</p>
  
  <p>Issue: I have a <code>1 (lending) - N (contracts)</code> relation. I'd like to call <code>lending.current_contract</code> which would return the last relevant contract.
  Optimization is also an issue. I'd like to call <code>:lending, :include =&gt; :contracts</code> without having to use separate queries for contracts which are already in the contracts array containing all contracts.</p>
  
  <p>Bad solution 1:</p>
  
  <pre><code>has_one :current_contract, :class_name =&gt; "Contract"
  </code></pre>
  
  <p>This doesn't work because every time I create, update or destroy it has to update the parent lending as well. Doing this I get a callback mess. For example when creating a lending, it also creates the first contract. For some reason going back and forth using callbacks for both the lending as its contract doesn't work.</p>
  
  <p>Bad solution 2:</p>
  
  <pre><code>def current_contract
    return if contracts.relevant.empty?
    @current_contract = contracts.relevant.last
  end
  </code></pre>
  
  <p>Sends a copy and not the reference. So <code>lending.current_contract.status = value</code> doesn't work.</p>
  
  <p>Is there some design pattern which I should look at? And are there some examples? I've looked at some github projects but none of them had similar problems solved, therefore I think it is a design problem.</p>