Read more

Rails 3 routing: Be careful with matching routes *including their format*

Dominik Schöler
May 21, 2012Software engineer at makandra GmbH

Today, this line made me trouble. Can you spot the mistake?

match 'sitemap.xml' => 'feeds#sitemap', :constraints => { :format => 'xml' }, :as => 'sitemap'
Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

The mistake is to match sitemap.xml. Rails will by default strip any dot-anything, remember it as desired format and forward the rest of the request to the routing engine. Since we're making .xml part of the match, it is not available for format determination and Rails will set the format to html.

Unfortunately, the constraint won't complain in this case and Rails even renders the sitemap.builder file correctly. My problem only occurred when I wanted to render a customized error page explicitly asking for the format.

So, the correct line would be:

match 'sitemap' => 'feeds#sitemap', :constraints => { :format => 'xml' }, :as => 'sitemap'

This works in Rails 3.

Posted by Dominik Schöler to makandra dev (2012-05-21 12:04)