加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在rails app上为ruby创建google站点地图的推荐

发布时间:2020-12-17 03:50:50 所属栏目:百科 来源:网络整理
导读:我做了一个快速的谷歌搜索,并没有看到任何超级伟大的自动创建和更新我的谷歌站点地图为 ruby on rails应用程序.有什么建议? 解决方法 我刚刚在博客应用程序中添加了动态站点地图.这些步骤可以帮助您入门. 将此路由添加到config / routes.rb文件的底部(应在
我做了一个快速的谷歌搜索,并没有看到任何超级伟大的自动创建和更新我的谷歌站点地图为 ruby on rails应用程序.有什么建议?

解决方法

我刚刚在博客应用程序中添加了动态站点地图.这些步骤可以帮助您入门.

将此路由添加到config / routes.rb文件的底部(应在其上方列出更具体的路由):

map.sitemap '/sitemap.xml',:controller => 'sitemap'

创建SitemapController(app / controllers / sitemap_controller):

class SitemapController < ApplicationController
  layout nil

  def index
    headers['Content-Type'] = 'application/xml'
    last_post = Post.last
    if stale?(:etag => last_post,:last_modified => last_post.updated_at.utc)
      respond_to do |format|
        format.xml { @posts = Post.sitemap } # sitemap is a named scope
      end
    end
  end
end

– 正如您所看到的,这适用于博客,因此使用Post模型.

这是视图模板(app / views / sitemap / index.xml.builder):

base_url = "http://#{request.host_with_port}"
xml.instruct! :xml,:version=>'1.0'
xml.tag! 'urlset','xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9' do
  for post in @posts do
    xml.tag! 'url' do
      xml.tag! 'loc',"#{base_url}#{post.permalink}"
      xml.tag! 'lastmod',post.last_modified
      xml.tag! 'changefreq','monthly'
      xml.tag! 'priority','0.5'
    end
  end
end

而已!您可以通过在浏览器中显示http://localhost:3000/sitemap.xml(如果使用Mongrel)或者使用cURL来测试它.

请注意,控制器使用陈旧?如果自上次请求站点地图以来没有新帖子,则发出HTTP 304未修改响应的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读