Rails sitemap.xml generation dynamically


config/routes.rb
#....

get 'sitemap.xml', :to => 'pages#sitemap', :defaults => {:format => 'xml'}

#....
app/controllers/pages_controller.rb
class PagesController < ApplicationController
  def sitemap
    headers['Content-Type'] = 'application/xml'
    
    respond_to do |format|
      format.xml {@posts = Post.all}
    end
  end
end
app/views/pages/sitemap.xml.erb
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc><%= root_url %></loc>
    <lastmod><%= Time.now.strftime('%Y-%m-%d') %></lastmod>
    <changefreq>daily</changefreq>
    <priority>1</priority>
  </url>
  <% for post in @posts %>
    <url>
      <loc><%= post_url(post) %></loc>
      <lastmod><%= post.updated_at.strftime('%Y-%m-%d') %></lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.7</priority>
    </url>
  <% end %>
</urlset>

Share This Post