Checking out the Rails 3 Beta, Part II: Routing
Last week I introduced you to one of the features that’s been added in the latest version of the Ruby on Rails framework: the Bundler gem manager. This week, I want to delve a little deeper and show you some even cooler new stuff.
Before doing that, however, I should note that since I wrote Part I, the second beta of Rails 3 was released. This gives me a great opportunity to show off another advantage of using Bundler. Let’s say you were excited by my post last week, and decided to grab the beta and start building a new application. Now, you’d like to upgrade that app to use the new and improved beta 2. Simple. You just need to change the line:
gem "rails", "3.0.0.beta"
To instead read:
gem "rails", "3.0.0.beta2"
Run
bundle install
, and ta-da: your application is now running on the new and improved beta. With that done, it’s time to dig into another major change in Rails 3.
Routing
Routes have always been one of Rails’s strong points. For the uninitiated, routes (which live in your application’s routes.rb
file) are the way you tell Rails which URLs map to which functions. So, by writing, for example:
map.connect 'posts/:id', :controller => 'posts', :action => 'view'
You’ve connected a URL like posts/3
to the view
function in your posts
controller, passing in an id
to find the correct post. Of course, the above code is using the old and busted Rails 2 syntax. In Rails 3, you can write:
match 'posts/:id', :to => 'posts#view'
Not only is the new syntax much shorter, I think you’ll also find it to be more readable. You can say it in English: “match this URL to this action.” As you can see, you no longer need to specify the controller name and the action name as separate parameters; you can just write "controller#action"
and pass it in as a single string. Very cool.
Every aspect of Rails routing has been given an overhaul in Rails 3: routing the root of your application, handling redirects, imposing constraints on parameters, creating named routes — you name it. The changes aren’t just cosmetic, either: there’s a lot of functionality that was simply impossible with the old routing module. For a full breakdown of everything that’s new, you should check out Rizwan Reza’s extensive blog post on the topic at the Engine Yard blog.
Next week I’ll be taking the new ActiveRecord query API for a spin. Until then, grab yourself a copy of the beta and have a play. You’ll be hooked on Rails in no time.