Reputation: 4425
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?
Upvotes: 1
Views: 54
Reputation: 3268
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
Upvotes: 0
Reputation: 15530
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
Upvotes: 2