title: Ruby on Rails: Is there a way to find with ActiveRecord that will first try the cache and if it fails run a query?
body: <p>Let's say that I'm looking for a specific item in a has_many association.</p>
  
  <p>Is there a way to find that won't rehit the database if what I'm requesting is already cached?</p>
  
  <p>Here's my situation (which is not working and does not do what I requested):</p>
  
  <pre><code>class User
    has_many :friendships
  
    def some_function(buddy)
      f = friendships.detect{|friendship| friendship.user == self &amp;&amp; 
                                          friendship.friend == buddy}
      f.do_something
    end
  end
  </code></pre>
  
  <p>The function is susceptible to N+1 problems, but most of the time I will already have either used :include or preloaded the user's friendships elsewhere.  However, if I didn't do this, then this current function will fall back to requesting all the friendships, even though it only needs one.  The solution would seem to be something like this:</p>
  
  <pre><code>f = Friendship.find_by_user_id_and_friend_id id, buddy.id
  </code></pre>
  
  <p>However, this will hit the database again even if all the friendships are cached and I have what I need right there.</p>
  
  <p>Is there any way to either use the cached copy, or if none is available, search a specific record?</p>