1

i have a user which can have a lot of saved searches and a lot of tasks. i'm caching them using the following

- cache user do
  - user.tasks.each do |task|
    - cache task do
      # do something with task

- cache user do
  - user.saved_searches.each do |search|
    - cache search do
      # do something with search

i've added the option to update the user, via touch option, whenever any of these records are updated. the issue i want to clarify is this scenario:

i've updated a search which expires the cache for that search and in effect, the cache for user. since the cache for user has expired, user.tasks will be executed.

is there a way to prevent this?

I'm thinking of adding a key to cache user and manually expire the cache which I've been doing before I used the cache_digest gem but I can't figure out how to do that.

jvnill
  • 29,479
  • 4
  • 83
  • 86
  • Check out my previous answer to a very similar issue. http://stackoverflow.com/questions/15194270/rails-cache-key-generated-as-activerecordrelation/15206742#15206742 – Mark Stratmann Mar 13 '13 at 15:01
  • if i read your code right, `user.tasks` will still be executed. moreover, it will always be executed so it's a worse option that the current code. – jvnill Mar 13 '13 at 19:09

1 Answers1

0

Instead of using the user's cache key for expiring the collections, you can use the latest updated_at of the collections, as the Rails Guide on caching demonstrates. E.g.

- cache("user-tasks/#{user.id}-#{user.tasks.maximum(:updated_at).try(:to_i)}") do
  - user.tasks.each do |task|
    - cache task do
      # do something with task

- cache("user-searches/#{user.id}-#{user.saved_searches.maximum(:updated_at).try(:to_i)}") do
  - user.saved_searches.each do |search|
    - cache search do
      # do something with search
phillbaker
  • 1,518
  • 11
  • 22
  • it's the same with using `cache user`, `user.tasks` will still be executed when one task is updated – jvnill Mar 09 '15 at 01:12
  • Yes, which is probably what you want - you asked about not executing `user.tasks` when a _search_ is updated, which in this case it won't. – phillbaker Mar 12 '15 at 03:00
  • ah right. sorry, this question has been asked 2 years ago. although what you have may work, a big issue is it goes through all the tasks and saved searches everytime you hit that page. – jvnill Mar 12 '15 at 06:21