DEV Community

Marc
Marc

Posted on • Originally published at webdevchallenges.com on

How to add a dynamically generated sitemap with rails

The sitemap.xml file on my blog is generated dynamically because I want it to include my latest posts in it.

The way I did that is that in a controller (in my case the HomeController) I added an action which is empty:

class HomeController < ApplicationController
  def sitemap
  end
end
Enter fullscreen mode Exit fullscreen mode

The config/routes.rb file defines route route and explicitly sets the format:

get 'sitemap.xml', to: 'home#sitemap', format: 'xml', as: :sitemap
Enter fullscreen mode Exit fullscreen mode

The app/views/home/sitemap.xml.builder file then defines some static routes and also defines routes depending on database entries like posts.
These routes simply render the urls of static pages and dynamic ones (posts). Note how you can use the .xmlschema method on date objects which returns the correct format for sitemaps.
Also we are using the .find_each method because if we have a massive amount of posts later, loading them to memory with .each
might result in problems later.

xml.instruct! :xml, :version=>"1.0"
xml.tag! 'urlset', 'xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9', 'xmlns:image' => 'http://www.google.com/schemas/sitemap-image/1.1', 'xmlns:video' => 'http://www.google.com/schemas/sitemap-video/1.1' do
  xml.url do
    xml.loc root_url
  end
  xml.url do
    xml.loc imprint_and_privacy_policy_url
  end
  xml.url do
    xml.loc impressum_und_datenschutzerklaerung_url
  end

  Post.published.find_each do |post|
    xml.url do
      xml.loc show_post_url(post.slug)
      xml.lastmod post.updated_at.xmlschema
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Make sure your robots.txt file then points to that sitemap like this for search engines to find that file correctly.

Sitemap: https://webdevchallenges.com/sitemap.xml
Enter fullscreen mode Exit fullscreen mode

Top comments (0)