articles tagged with routing

Cleaning your Rails routes

no comments yet, post one now

After watching the excellent Rails Best Practices presentation by Wen-Tien Chang, I took the opportunity to perform this optimization on my apps. Basically removing the default Rails route mappings from routes.rb. If your Rails app is RESTful then you should have all your resource endpoints defined in routes; and be using the Rails url/path view helpers in your templates. If this is the case you can remove these default mappings at the base of your routes file;

# these can go!
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'

Doing this on my smaller Rails apps caused no problems, but in Bugle (a bigger app) I came across the following gotchas;

Look for urls or paths in your code that are defined with { :controller => :foo, :action => :bar } options, these should be replaced for the equivalent Rails helper for the controller – rake routes is your friend in figuring out what to use; eg.

url_for(:controller => 'blogs', :action => 'show' :id => @blog.id}
# should simply change to
blog_url(@blog) 
# or
blog_path(@blog)

Calls to link_to should again use the same urls/path helpers as above – but in some instances this became a “Route not found problem”;

link_to 'comment website', @comment.website
# where @comment.website is a String e.g. http://hallo.com
# instead ditch link_to and use simple HTML tags

Happily I was able to delete a large amount of unnecessary routing specs, that were essentially testing the behavior of the 7 standard RESTFul Rails routes. Rails 3 has a completely revamped routing system (see here for details), so making optimizations and cleaning up routes.rb prior to it’s release is advisable.

Related Links

January 21, 2010 12:18 by
← (k) prev | next (j) →