如何在rails 4中使缓存键失效

时间:2013-11-07 13:45:29

标签: ruby-on-rails ruby caching

我的应用使用Rails 4.0.0。 我有patcial模型users_posts

class UsersPost < ActiveRecord::Base
  attr_accessible :post_id, :user_id, :example
  belongs_to :post, touch: true

posts

class Post < ActiveRecord::Base
  has_many :users_posts

这是users_post视图:

-cache users_post do
  .box.col2
    p.center
      =status_post_vk(users_post)
      =status_post_fb(users_post) 
    p = check_box_tag "posts_ids[]", users_post.id
    p = best_in_place users_post.post, :text, type: :textarea
    p = raw users_post.post_url_small.map{|url| image_tag 'http://bla.com/'+url}.join()
    p 
      = link_to 'Show', users_post
      = link_to 'Edit', edit_users_post_path(users_post)
      = link_to 'Destroy', users_post, data: { confirm: 'Text' }, :method => :delete

如何更改缓存密钥,以便更改发布文本(更新DB中的属性文本)best_in_place users_post.post, :text, type: :textarea

1 个答案:

答案 0 :(得分:1)

您可以通过添加gem 'dalli'来完成此操作。 查看:

-cache ["#{current_user.id}",users_post], skip_digest: true do
  .box.col2
    p.center
      =status_post_vk(users_post)
      =status_post_fb(users_post) 
    p = check_box_tag "posts_ids[]", users_post.id
    p = best_in_place users_post.post, :text, type: :textarea
    p = raw users_post.post_url_small.map{|url| image_tag 'http://bla_bla.com/'+url}.join()
    p 
      = link_to 'Show', users_post
      = link_to 'Edit', edit_users_post_path(users_post)
      = link_to 'Destroy', users_post, data: { confirm: 'Text' }, :method => :delete

在控制器中添加expire_fragment,如下所示:

class PostsController < ApplicationController
  after_filter  :cache_clear, :only => [:create, :update, :destroy]

  def cache_clear
    expire_fragment /.*#{current_user.id}.*/
  end

更新后,创建或销毁缓存过期后。