Routing Nested Static Content in Rails
I’ve long used this little idiom to add “static” content pages to my Rails site.
map.connect ':action', :controller => 'content'
If you put this at the very end of your routes file, it will allow you to just drop .rhtml into views/content and have them show up with the corresponding URL automatically. The downside is that you try to generate the route with a helper (assuming the old-school standard route), you don’t get the cleanest URL.
url_for(:controller => 'content', :action => 'page') #returns /content/page instead of /page
Okay, so you can’t use the URL helper. But why would you want to anyway? Static pages aren’t going to change, and if they do, the
url_for indirection certainly isn’t going to help. Just keep it simple and merrily
link_to("Page", "/page"). Or even just write out the HTML explicitly… who am I to judge?
I’ve been pretty happy with this setup until today, when suddenly I’ve become extremely demanding of my routes. It turns out I wanted my content organized into subdirectories. So I’ve come up with a similarly elegant idiom to use for the future. It goes something like this:
in routes.rb: map.connect '*path', :controller => 'content', :action => 'show' in content_controller.rb: def show render :action => params[:path].join('/') end
Booya! Nested page content. Why do I think this is so cool? Because I like my content in HTML files.