Railsで動的にサイトマップを出力する Heroku対応
はじめに
サイトマップを設置するIssueを行いましたので備忘録として残しておきます。
Railsでsitemap作成と検索するとsitemap_generator
がまずヒットするのですが、今回はdynamic_sitemaps
を利用しま…せんでした。
Herokuで動いていた為に、動的にサイトマップを出力する形にしました。
作業内容をざっくり
routeに追記
get 'sitemap' => 'main#sitemap'
controllerに追加
@routes = Route.select(:id, :created_at)
viewとhelperを追加
sitemap.xml.builder
xml.instruct! xml.urlset(xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9') do sitemap(xml, root_url, lastmod: Time.current, changefreq: 'always', priority: 1.0) sitemap(xml, routes_url, lastmod: Time.current, changefreq: 'daily', priority: 0.8) @routes.each do |route| sitemap(xml, route_url(route.id), lastmod: route.created_at) end end
sitemap_helper.rb
module SitemapHelper def sitemap(xml, path, lastmod: nil, changefreq: nil, priority: nil) xml.url do xml.loc(path) xml.lastmod(lastmod.xmlschema) if lastmod.present? xml.changefreq(changefreq) if changefreq.present? xml.priority(priority) if priority.present? end end end