99miles
99miles

Reputation: 11222

How to render sitemap.xml in rails app

I have added /views/sitemap/index.xml and want it displayed when i go to the relevant url.

class SitemapController < ApplicationController

  def index
    respond_to do |format|
      format.html
      format.xml
    end
  end

end

And in routes.rb

  match "sitemap/" => "sitemap#index"

Using Rails 3

When I go to mydomain.com/sitemap/ I just get a white page. Any ideas?

index.xml

<?xml version="1.0" encoding="UTF-8"?>
<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

<url>
  <loc>http://www.mydomain.com/</loc>
  <changefreq>weekly</changefreq>
</url>
</urlset>

Upvotes: 2

Views: 2808

Answers (2)

Rishav Rastogi
Rishav Rastogi

Reputation: 15492

Problem is that you are using your index action to render xml and it will render "index.xml" file not "sitemap.xml" which is what you have created in your views

While your routes are correct, you are using the wrong filename in views

Try renaming sitemap.xml file to index.xml ( in the views/sitemap folder)

If you define name routes, you need to define :format with it

match "/sitemap/sitemap.[:format]", :to => "sitemap#index" 

it will pickup your format from there. Also you can define a default format in the routes

match "sitemap/sitemap.xml", :to => "sitemap#index", :defaults => {:format => :xml}

Upvotes: 1

konung
konung

Reputation: 7038

I may be wrong , but I see 2 reasons:

  1. index action doesn't actually do anything judging by this code sample, it just responds back with no info.

  2. you need to render your object as xml - if you don't rails, doesn't know you want xml - it just treats it as another file extension. It actually lets you do little tricks - like sending json to an xml request ( thou I have no idea why would anyone try to do that). Thou one useful application is that you can make rails send custom rendering of an object to a common format or render regular data in common format for an unusual extension ( we had a client who wanted csv data for a .dat request)

Here is a short example, from a sample home controller:

class HomeController < ApplicationController
  def index

    @m = {
    :color => "yellow",
    :total => "20"
  }

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @m}
    end

  end

end

this returns this object as xml:

<hash>
 <total>20</total>
 <color>yellow</color>
</hash>

Upvotes: 0

Related Questions