Monday, September 7, 2009

Rails Magic - Part 1

I have heard a lot about the magic in Rails without really experiencing it until today. In Django, url names are explicitly defined in the urls.py file, for instance stories-index is the url name for stories/:
url(r'stories/$', stories_view, name='stories-index')
In Rails, there is a built-in url helper which will automatically generate those route names, my routes.rb is:
ActionController::Routing::Routes.draw do |map|
map.resources :stories
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
The route name to stories is stories_path, the module ActionController::Resources take care of that. Here's a sample usage of the stories route name, stories_path:
def create
@story = Story.new(params[:story])
@story.save
redirect_to stories_path
end
You can check those route names with the following command at the CLI:
rake routes
You still have to suffix the displayed names with _url or _path. It's not a bad thing to see some automatic name generation but the rails developer will have to be aware of it.

No comments: