Rails expire fragment cache from models

2019-06-20 22:42发布

I am working with cache in my Rails project and wants to expire the cache of a particular url. I got the following command to expire fragment corresponding to the URL passed:

ActionController::Base.new.expire_fragment("localhost:3000/users/55-testing-devise/boards/")

I am confused where to put this code in my Rails project so that it gets executed as soon as the url in a text field is added and expire button is clicked.

3条回答
霸刀☆藐视天下
2楼-- · 2019-06-20 22:52

The ActionController::Caching::Sweeper is a nice way to do this, its part of Rails observer.

http://api.rubyonrails.org/classes/ActionController/Caching/Sweeping.html

class MyModelSweeper < ActionController::Caching::Sweeper
  observe MyModel

  def after_save(object)
    expire_fragment('...')
  end
end
查看更多
迷人小祖宗
3楼-- · 2019-06-20 23:05

The expire_fragment won't work, as you don't have the digest added to the key. See DHH here: https://github.com/rails/cache_digests/issues/35

I've posted a related answer about caching a json response: https://stackoverflow.com/a/23783119/252799

查看更多
Viruses.
4楼-- · 2019-06-20 23:11

You should probably consider a different approach. Models should not be concerned with how caching works, and traditionally the whole sweeper approach tends to become complex, unwieldy and out of sync with the rest of the code.

Basically, you should never have to expire fragments manually. Instead, you change your cache key/url once your model is updated (so that you have a new cache entry for the new version).

Common wisdom nowadays is to use the Russian Doll Caching approach. The link goes to an article that explains the basics, and the upcoming Rails 4 will contain even better support.

This is probably the best way to go for the majority of standard Rails applications.

查看更多
登录 后发表回答