简体   繁体   中英

Rails 3.2 cache not working

I'm using Rails.cache.write and Rails.cache.read to store some activerecord objects, but it not seems to be workinkg.

posts = Post.find(...)
Rails.cache.write(myKey, posts)

... next request...

foo = Rails.cache.read(myKey)

Despite variable foo is correctly filled, this generate the same sql logs. If I change database during "...", I got news results.

What could be happen?

It is recommended to cache serialised data (results only), not an ActiveRecord object with its own class name and individual object id.

Fetch technique is also preferred

Rails.cache.fetch(myKes) do
  Post.find(...).as_json
end 

Try this. it will expire in 30 secs.

Rails.cache.fetch("posts_for_#{myKey}", expires_in: 30.seconds) do
  posts = Post.find(...)
  posts
end

put this in some kind of method and pass that method myKey and ... for posts and it should work. it will return from cache if exists else query on it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM