title: How to make Low-Level caching collaborate with Association caching in Rails?
body: <p>I am currently working on a project with Rails 5. I want to boost the performance, so I decided to use Low-Level caching like the following:</p>
  
  <pre><code>class User &lt; ApplicationRecord
    has_one :profile
  
    def cached_profile 
      Rails.cache.fetch(['Users', id, 'profile', updated_at.to_i]) do
        profile
      end
    end
  end
  
  class Profile &lt; ApplicationRecord
    belongs_to :user, touch: true
  end
  </code></pre>
  
  <p>It works fine respectively. But now I want to make the two caches to collaborate. What I want is that the associated object doesn't need to be retrieved from the database once it is retrieved from the cache store(redis here).</p>
  
  <pre><code>irb&gt; u = User.take
  irb&gt; u.cached_profile # fetch from the redis. Can I set the association caching in `cached_profile`?
  irb&gt; u.profile # fetch from the database
    Profile Load (1.4ms) SELECT  "profiles".* FROM "profiles" WHERE "profiles"."user_id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  irb&gt; u.profile # fetch from the association caching
  </code></pre>
  
  <p><code>u.profile</code> shouldn't fetch from the database because of it's already retrived from the redis, how to achieve this?</p>
  
  <p><strong>Update 1:</strong></p>
  
  <p>I found that there's an instance variable <code>@association_cache</code> in the instance of <code>ActiveRecord::Base</code>, which stores cached associations and determines if an association should be retrieved from the database.</p>
  
  <p>I think I could do something like <code>user.instance_variable_get(:@association_cache)['profile'] = cached_profile</code> to make it work. But the value in the <code>@association_cache</code> is an instance of <code>ActiveRecord::Associations::HasOneAssociation</code> and I don't know how to build the <code>user</code> to it currently.</p>