如何将caches_action配置为适用于多种格式?

时间:2009-09-27 16:13:05

标签: ruby-on-rails ajax caching memcached

我有一个rails动作,它以各种格式响应请求,包括AJAX请求,例如:

   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

我已使用memcached将此操作设置为缓存:

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

这种模式似乎适用于缓存HTML结果,但不适用于JS结果。当JS部分不是来自缓存时,它总能正常工作。但是,当有缓存命中时,页面不会更新。

可能导致此问题的原因是什么?

更新:深入研究这一点,看起来缓存中的请求获取mime类型'text / html'而不是'text / javascript'。但是我不知道如何解决这个问题 - 它是memcached的怪癖吗? (Rails 2.3.2)

3 个答案:

答案 0 :(得分:2)

与voldy的回答相似,但使用了不推荐的方法。

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

答案 1 :(得分:0)

我认为我有类似的问题,我经历过,如果我将渲染:更新块移出到rjs文件中,请求会更快。如果我像这样进行渲染,响应时间大约是8秒,在移出到rjs模板后它是80ms。我真的不太了解memcached,但对我而言,他似乎只能缓存视图,如果您对缓存控制器有任何想法请与我分享。

答案 2 :(得分:0)

即使在edge(3.0.1)版本中,rails中也有issue

我可以解决这个问题:

  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