--- layout: page status: publish published: true title: Ruby on Rails Sitemap Generator author: display_name: Tony Primerano login: admin email: primerano@tonycode.com url: http://openid.aol.com/tonyprimerano author_login: admin author_email: primerano@tonycode.com author_url: http://openid.aol.com/tonyprimerano wordpress_id: 304 wordpress_url: http://blog.tonycode.com/?page_id=304 date: '2011-12-20 21:17:23 -0500' date_gmt: '2011-12-21 02:17:23 -0500' categories: [] tags: [] comments: [] ---

How to build a sitemap for your rails app.

This wiki entry was the basis for my sitemap recipe in Advanced Rails Recipies

Related blog posts

The following example will build a sitemap for a single model but it can easily be extended.


class SitemapController < ApplicationController
  def sitemap
    @entries = YourModel.find(:all, :order => "updated_at DESC", :limit => 50000)
    headers["Content-Type"] = "text/xml"
    # set last modified header to the date of the latest entry.
    headers["Last-Modified"] = @entries[0].updated_at.httpdate    
xml.urlset "xmlns" => "http://www.sitemaps.org/schemas/sitemap/0.9" do
  @entries.each do |entry|
    xml.url do
      xml.loc url_for(:controller => 'controller you use to show the model', 
                      :action => 'show', 
                      :id => entry.id,
                      :only_path => false)
      xml.lastmod entry.updated_at.to_date
only_path => false is necessary as sitemaps are required to have protocol and domain.


using a sitemap index

If you have over 50000 URLs you need to use a sitemap index file. I'll put an example here eventually.  ;-)