Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7443443
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T11:19:50+00:00 2026-05-29T11:19:50+00:00

I’m trying to cache an ActiveRecord with its association. The problem is there’s a

  • 0

I’m trying to cache an ActiveRecord with its association. The problem is there’s a database query when accessing the associations on a retrieved record.

Normally, I’d just cache with eager-loading Rails.cache.write('post', Post.includes(:comments).find(99)). This seems to work, but the problem is I only want to cache a limited subset of the association, and limits are ignored when eager-loading (mentioned here for example). So Post.includes(:popular_comments).find(99) would return all comments, not just the popular ones.

So I’ve tried caching the object after lazy-loading the association, but a query unfortunately occurs when pulling the objects out:

class Post < ActiveRecord::Base
  has_many :comments
  has_many :popular_comments, :class_name > 'Comment', :limit => 20, :order => :votes

post = Post.find(99)
post.popular_comments # lazy-load limited associations
Rails.cache.write('post', post)
...
Rails.cache.read('post').popular_comments # Unwanted SQL query :(

I’ve tried caching a clone instead, same unwanted SQL query. And I’ve tried this with both redis and memcached implementations, same result. Oddly, this sequence does work on console afaict, but a simple usage in a controller or view like above fails (ie SQL occurs).

Update (April 2017): I would now say this is a silly premise. Caching whole objects is generally wasteful as it uses a lot of cache storage and it’s slow to serialise/deserialise them. Caching associations as well (as asked in this question) is multiplying that wastage by N. Usually it’s more efficient to just cache raw IDs and HTML fragments.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T11:19:51+00:00Added an answer on May 29, 2026 at 11:19 am

    Try post.popular_comments.reload

    First, limits are in fact ignored when eager loading. From the docs:

    If you eager load an association with a specified :limit option, it will be ignored, returning all the associated objects

    This means, like you discovered, you have to force the association into the parent object yourself. In my experiments, post.popular_comments didn’t work (this makes sense, since it returns a proxy object), and interestingly neither did post.popular_comments.all. post.popular_comments(true) does the trick, however. Underneath that code calls reload, and simply doing post.popular_comments.reload also gets the association loaded into the parent class.

    I’m not sure which of these two is more correct, post.popular_comments(true) or post.popular_comments.reload. Both seem a bit brittle, but the second one reads nicer and expresses your intent more clearly.

    I validated that both these methods:

    1. stored the limited association in memcache
    2. did not trigger a SQL query after loading from cache

    My script to store the post:

    require 'pp'
    Rails.cache.clear
    post = Post.first
    
    #post.popular_comments(true)
    post.popular_comments.reload
    
    Rails.logger.info "writing to cache"
    s = Rails.cache.write "post", post
    Rails.logger.info "writing to cache done"
    

    And to retrieve:

    require 'pp'
    Rails.logger.info "reading from cache"
    post = Rails.cache.read "post"
    Rails.logger.info "reading from cache done"
    Rails.logger.info post.popular_comments.inspect
    

    If I run one after the other my log shows:

      Post Load (0.5ms)  SELECT `posts`.* FROM `posts` LIMIT 1
      Comment Load (0.5ms)  SELECT `comments`.* FROM `comments` WHERE `comments`.`post_id` = 1 ORDER BY votes LIMIT 20
    writing to cache
    writing to cache done
    reading from cache
    reading from cache done
    [#<Comment id: 1, ...
    

    My mySQL log also confirms that the second script does not trigger a query for the association.

    This was done with Rails 3.1.1

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am currently running into a problem where an element is coming back from
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
I'm trying to create an if statement in PHP that prevents a single post

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.