sql
iphone
css
c
ajax
mysql
database
linux
regex
objective-c
silverlight
flash
json
perl
facebook
cocoa
php5
asp
api
jsp
Try post.popular_comments.reload
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.
post.popular_comments
post.popular_comments.all
post.popular_comments(true)
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:
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
I am not seeing the problem that you described in my tests.
Code that I have used in controller
def show unless Rails.cache.exist?('faq_category') @faq_category = Faq::Category.first @faq_category.questions Rails.cache.write('faq_category', @faq_category) end @faq_category = Rails.cache.read('faq_category') end
When I run the page I see the following statements in log which says that the models are not getting reloaded Larger image available at https://skitch.com/aroop/g9w5t/untitled
The problem could be with your view file. Comment the view and see if the problem is still there.