Darwinweb

Routing Nested Static Content in Rails

June 9, 2007     

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.

vish says…
July 27, 2007 at 11:02PM

Hello,

I added the *path route like what you wrote here to the bottom of my routes.rb (putting it higher gave me problem routing to mysite/somecontroller). I get my static content to show but Rails also complains in the log (with a huge stack trace) about missing Template file. Example:
ActionController::MissingTemplate (Missing template ./script/../config/../app/views/documents/uploaded/Sample_v_3.doc.rhtml)

The static file I was getting to in the above exampe was http://localhost:3000/uploaded/Sample_v_3.doc

Did you see any such errors? Else, what may I be doing wrong?

Thanks in advance for your response

Gabe da Silveira says…
July 28, 2007 at 12:11AM

Sorry for the confusion here. The term “static” here is a bit of a misnomer. What I really mean is content for which there doesn’t need to be a controller action, but which we still want to display inside the application layout.

It looks like you are trying to reference an actual static file, in which case it should be served up through Apache (or whatever primary server you’re using) by placing it in the public directory. If you put it in /public/uploaded/Sample_v_3.doc it will be served before the process even hits Rails with huge performance gains.