How can caches_action be configured to work for multiple formats?

主宰稳场 提交于 2019-12-06 06:25:06

问题


I have a rails action which responds to requests in various formats including AJAX requests, for example:

   def index
    # do stuff
    respond_to do |format|
      format.html do
        # index.html.erb
      end
      format.js do
        render :update do |page|
          page.replace_html 'userlist', :partial => "userlist", :object=>@users
          page.hide('spinner')
          page.show('pageresults')
        end
      end
    end
   end

I have set this action to cache using memcached using:

 caches_action :index, :expires_in=>1.hour, :cache_path => Proc.new { |c| "index/#{c.params[:page]}/#{c.request.format}" }

This pattern seems to work fine for caching the HTML result but not for the JS result. The JS part always works fine when it is not coming from the cache. However when there is a cache hit, the page does not update.

What could cause this and what is the fix?

Update: digging into this more it looks like requests from the cache get mime type 'text/html' instead of 'text/javascript'. However I'm not sure how to fix this - is it a quirk of memcached? (Rails 2.3.2)


回答1:


Similar to voldy's answer but using non-deprecated methods.

caches_action :show,
              :cache_path => :post_cache_path.to_proc,
              :expires_in => 1.hour

protected

def post_cache_path
  if request.xhr?
    "#{request.url}.js"
  else
    "#{request.url}.html"
  end
end



回答2:


I think I have similar problem, I experienced that if I move out the render :update block into an rjs file the request will be much faster. If i do the rendering like this the response time was around 8 sec, after moving out to an rjs template it was 80ms. I dont really know much about memcached, but for me it seems that he is able only to cache the views, if you have any thoughts about caching a controller please share with me.




回答3:


There is an issue in rails even in edge (3.0.1) version.

I could workaround it with this:

  caches_action :show, :cache_path => :show_cache_path.to_proc

  private

  def show_cache_path
    if request.accepts[0].to_sym == :html
      "#{request.host_with_port + request.request_uri}.html"
    else
      "#{request.host_with_port + request.request_uri}.js"
    end
  end


来源:https://stackoverflow.com/questions/1483847/how-can-caches-action-be-configured-to-work-for-multiple-formats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!