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

Posted Almost 12 years ago. Visible to the public.

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

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

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.

Dominik Schöler
Last edit
About 11 years ago
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2012-05-21 10:04)