1

I use the following fragment cache:

app/views/people/index.html.erb

<% cache do %>
  <p>foobar</p>
<% end %>

That cache gets stored in views/localhost:3000/people/936e34304c10cd4b7469d805b7070ac4

I'd like to expire that cache with an after_update callback in the Person model but can't get it working.

app/models/person.rb

class Person < ActiveRecord::Base
  after_update :sweep_cache

  private
  def sweep_cache
    ActionController::Base.new.expire_fragment(controller: 'people',
                                               action: 'index')
  end
end

This code leads to this error:

Screenshot of the RuntimeError

Adding include Rails.application.routes.url_helpers to the method doesn't help. What is the correct code for the sweep_cache method to work?

wintermeyer
  • 8,178
  • 8
  • 39
  • 85
  • possible duplicate of [Rails expire fragment cache from models](http://stackoverflow.com/questions/16273922/rails-expire-fragment-cache-from-models) – dgilperez Feb 23 '15 at 16:02
  • There is no answer for this question. – wintermeyer Feb 23 '15 at 16:05
  • Well, I think there is, in fact it's exactly the same question. There you can read about how calling ``ActionController::Base.new.expire_fragment`` from a model it's not the way to go, and also how you should consider other approaches such as sweepers or russian doll caching. – dgilperez Feb 23 '15 at 16:10
  • That code is wrong, and you are misunderstanding how cache expiring works. I suggest you read a bit more about the topic and its best practices, instead of stubbornly trying to force wrongly-though code to work. In other words, and trying to be as specific as you require: the specific solution for your specific problem involves refactoring your code to remove your specific `sweep_cache` after_update, and moving that logic either to a ``sweeper`` or just not expiring it at all and just use a russian doll cache approach to caching. – dgilperez Feb 23 '15 at 19:21
  • 1
    Having said that, if you still choose to try that controller-only code to work in a model, you can try to add ``include Rails.application.routes.url_helpers`` to the class, not to the method. It's probable that a subsequent error will pop up, or maybe not. – dgilperez Feb 23 '15 at 19:23
  • 1
    Just curious: did you manage to make this work? – dgilperez Feb 25 '15 at 13:18
  • No. This was to see how much more work it would be. I'd never go this way. It was research work for this screencast about fragment caching: http://www.amooma.de/screencasts/2015-02-24-fragment-caching-rails-4.2/ – wintermeyer Feb 25 '15 at 14:18
  • 1
    Good to know. Nice screencast btw. – dgilperez Feb 25 '15 at 14:43

0 Answers0