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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️