Manually Clear Fragment Cache in Rails

后端 未结 4 1929
攒了一身酷
攒了一身酷 2021-02-07 00:53

I\'m using Memcached with Heroku for a Rails 3.1 app. I had a bug and the wrong things are showing - the parameters were incorrect for the cache.

I had this:

相关标签:
4条回答
  • 2021-02-07 01:00

    From the rails console:

    Rails.cache.delete 'FRAGMENT-NAME'
    
    0 讨论(0)
  • 2021-02-07 01:00

    Here you are:

    <% ActionController::Base.new.expire_fragment("foo_header_cache_#{@user.id}") %>
    

    Reference:
    - How to call expire_fragment from Rails Observer/Model?

    0 讨论(0)
  • 2021-02-07 01:08

    I ended up manually clearing the entire cache by going into the rails console and using the command:

    Rails.cache.clear
    
    0 讨论(0)
  • 2021-02-07 01:14

    From the console:

    You can run this (ie. if you know the id is '1')

    ActionController::Base.new.expire_fragment("foo_header_cache_1")
    

    To use Rails.cache.delete you need to know the fragment name. In your case, it would be

    Rails.cache.delete("views/foo_header_cache_1") # Just add 'views/' to the front of the string
    

    If you have an array-based cache key using objects, such as:

    cache([:foo_header_cache, @user])
    

    Then you can get the fragment name like so

    ActionController::Base.new.fragment_cache_key([:foo_header_cache, @user])
    

    The name includes the id and updated_at time from any objects (to the yyyymmddhhmmss). It would be something like "views/foo_header_cache/users/1-20160901021000"

    Or simply clear it using the array.

    ActionController::Base.new.expire_fragment([:foo_header_cache, @user])
    
    0 讨论(0)
提交回复
热议问题