我有一个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)
发布于 2012-05-07 08:18:36
与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
发布于 2009-12-18 17:06:40
我想我也有类似的问题,我经历过如果我把render :update块移到一个rjs文件中,请求速度会快得多。如果我像这样渲染,响应时间大约是8秒,移到rjs模板后是80ms。我真的不太了解memcached,但对我来说,他似乎只能缓存视图,如果你对缓存控制器有任何想法,请与我分享。
发布于 2010-11-09 05:17:09
甚至在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
https://stackoverflow.com/questions/1483847
复制相似问题