2015-11-03 32 views
1

我在我的rails 4项目中使用了片段缓存。我有个城市控制器和city_sweeper缓存清理器不能用于自定义方法Rails 4

cities_controller.rb 
    cache_sweeper :city_sweeper, :only => [:update, :destroy] 
    . 
    . 
    def update_featured 
    @city = City.unscoped.find(params[:id]) 
    if params[:featured] 
     @city.update_attribute(:featured, params[:featured]) 
    end 
    render :text => "success: 
    end 
    . 
end 

,在我city_sweeper.rb我有这样的代码

class CitySweeper < ActionController::Caching::Sweeper 
observe City 

def after_update(city) 
    expire_cache(city) 
end 

def after_destroy(city) 
    expire_cache(city) 
end 

def after_update_featured(city) 
    expire_cache(city) 
end 

def expire_cache(city) 
    expire_fragment "city_index_#{city.id}" 
end 
end 

其工作细跟CRUD操作,但它不工作了我的自定义method.its叫我扫地机.rb,但我没有在那里获得城市对象。我收到此错误:

NoMethodError (undefined method `expire_fragment' for #<CitySweeper:0xab9f1e0 @controller=nil>): 
+0

显示您的视图部分 – Prashant4224

+0

你需要到期fragment cache使用像'expire_fragment(:controller => 'cities',:action =>'index', :action_suffix =>'all_cities)' – Prashant4224

+0

my view part => - if @ cities.present? - @ cities.each do | city | - cache“city_index _#{city.id}”,skip_digest:true do –

回答

0

您可以使用此

UPDATE

if @cities.present? 
    @cities.each do |city| 
    cache(action: 'recent_update',key: "city_index_#{city.id}", skip_digest: true) do 
    ... 
    end 
    end 
end 

在扫地

class CitySweeper < ActionController::Caching::Sweeper 
    observe City 

    ..... 
    def expire_cache(city) 
    expire_fragment(controller: 'cities', action: 'recent_update',key: "city_index_#{city.id}") 
    end 
end 
+0

但是当我调用自定义方法update_feature时,city对象通过update_attribute进行更新,当时它的未到期片段 –

+0

我得到这个error:NoMethodError:未定义方法'expire_fragment'for# from /home/hemant/.rvm/gems/ruby-2.0.0-p643/gems/rails-observers-0.1.2/ lib/rails/observers/action_controller/caching/sweeping.rb:105:in'method_missing' –