Swati Aggarwal
Swati Aggarwal

Reputation: 1275

Rails expire fragment cache from models

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.

Upvotes: 5

Views: 4250

Answers (3)

oma
oma

Reputation: 40780

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

Upvotes: 2

averell
averell

Reputation: 3782

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.

Upvotes: 7

Charles Barbier
Charles Barbier

Reputation: 845

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

Upvotes: 3

Related Questions