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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)