ruby-on-rails – 耙子任务中的render_to_string

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 耙子任务中的render_to_string前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用Rake任务来缓存我的站点地图,以便对sitemap.xml的请求不会永远存在.这是我到目前为止
  1. @posts = Post.all
  2.  
  3. sitemap = render_to_string :template => 'sitemap/sitemap',:locals => {:posts => @posts},:layout => false
  4. Rails.cache.write('sitemap',sitemap)

但是当我尝试运行它,我得到一个错误

  1. undefined local variable or method `headers' for #<Object:0x100177298>

如何将模板从Rake中渲染为字符串?

解决方法

这是我如何做到的:
  1. av = ActionView::Base.new(Rails::Configuration.new.view_path)
  2. av.class_eval do
  3. include ApplicationHelper
  4. end
  5.  
  6. include ActionController::UrlWriter
  7. default_url_options[:host] = 'mysite.com'
  8.  
  9. posts = Post.all
  10.  
  11. sitemap = av.render 'sitemap/sitemap',:posts => posts
  12. Rails.cache.write('sitemap',sitemap)

请注意,我将模板转换为部分,以使其工作

猜你在找的Ruby相关文章