Dynamically generated sitemap in rails

Site Map path can be defined in robots.txt in your root. For example:

Sitemap: https://calvin.my/my_sitemap.xml
User-agent: *
Disallow:

To dynamically generate this file, you will need to add an entry in your routes.rb file.

get '/my_sitemap', to: 'main#sitemap'

Create a controller action to render the file.

def sitemap
  @posts = Post.order(:created_at => :desc)
  result = render_to_string('main/sitemap.xml.builder')
  send_data(result, :disposition => 'inline', :type=>'text/xml',:filename => 'sitemap.xml')
end

If you do not want to generate for every request, you can cache (for example using Redis) and expires every 15 minutes.

Next, you need to define an XML builder template under your view folder. For example, sitemap.xml.builder

xml.instruct!
xml.urlset('xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9') do
  # The static paths
  xml.url do
    xml.loc 'https://calvin.my/'
    xml.changefreq 'daily'
  end
  # The dynamic paths
  @posts.each do |post|
    xml.url do
      xml.loc "https://calvin.my/posts/#{post.id}"
      xml.lastmod "#{post.updated_at.strftime('%F')}"
      xml.changefreq 'daily'
    end
  end
end

And that is all. Whenever a get sitemap request is called, the latest sitemap is returned. For example, take a look at the sitemap of this site.

Learn more about the protocol here.


AI Summary
Chrome On-device AI 2024-12-06 19:48:29

Share Article