Making a sitemap.xml with Ruby on Rails 4
Asked Answered
R

1

8

I am trying to make a sitemap for my Ruby on Rails 4 application. I would use a gem like this dynamic_sitemaps but I can't use it with Heroku so I looked around and found this tutorial: http://meghagulati.com/2013/12/05/sitemap-xml-on-heroku-with-ruby-on-rails/ to make my own (with small changes) But I am getting this error when I go to myapp.com/sitemap.xml, I hope someone can help me to find the error.

ActionController::UnknownFormat in SitemapsController#index ActionController::UnknownFormat Extracted source (around line #7): respond_to do |format|

#app/controllers/sitemaps_controller.rb
class SitemapsController < ApplicationController
  def index
    @static_pages = [root_url]
    @movies = Movie.all
    respond_to do |format|
      format.xml
    end
    @series = Series.all
    respond_to do |format|
      format.xml
    end
  end
end

#app/views/sitemaps/index.xml.builder
base_url = "http://#{request.host_with_port}"
xml.instruct! :xml, :version=>'1.0'
xml.tag! 'urlset', 'xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9' do
  xml.url{
      xml.loc("http://myapp.com")
      xml.changefreq("weekly")
      xml.priority(1.0)
  }
  xml.url{
      xml.loc("http://myapp.com/movies")
      xml.changefreq("daily")
      xml.priority(0.9)
  }
  xml.url{
      xml.loc("http://myapp.com/series")
      xml.changefreq("daily")
      xml.priority(0.9)
  }
  @movies.each do |movie|
    xml.url {
      xml.loc "#{movie_url(movie)}"
      xml.lastmod movie.updated_at.strftime("%F")
      xml.changefreq("weekly")
      xml.priority(0.5)
    }
  end
  @series.each do |series|
    xml.url {
      xml.loc "#{series_url(series)}"
      xml.lastmod series.updated_at.strftime("%F")
      xml.changefreq("weekly")
      xml.priority(0.5)
    }
  end
end

#config/routes.rb
resources :sitemaps, :only => :index
get "sitemap.xml" => "sitemaps#index", format: :xml, as: :sitemap
Retsina answered 24/5, 2014 at 20:28 Comment(0)
N
8

First of all, you respond_to must only be called once, so you need to change your controller method, e.g.:

class SitemapsController < ApplicationController
  def index
    @static_pages = [root_url]

    @movies = Movie.all
    @series = Series.all

    respond_to do |format|
      format.xml
    end
  end
end

This change should render an XML file in your browser when you visit the following URL:

http://lvh.me:3000/sitemaps.xml

Furthermore, you need to change your routes specification and use a string for the format rather than a symbol, i.e. change :xml to "xml":

  get "sitemap.xml" => "sitemaps#index", :format => "xml", :as => :sitemap

You should see the same XML file in your browser when visiting the following URL:

http://lvh.me:3000/sitemap.xml

(lvh.me resolves to localhost)

Nonflammable answered 25/5, 2014 at 13:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.