While working on a problem recently, we realized that it would be extremely helpful to be able to test some of our restful routes via the console. So after a bit of hunting we found an excerpt from The Rails Way that did exactly what we needed it to. A few simple steps and you’ll be ready to go in no time. FYI, the following is tutorial-lite and assumes you already have a grasp of some of the basics of rails routing functionality. Onward…
Let’s create a simple project that we can use for demonstration purposes:
#: rails restful_routes
#: cd restful_routes
If you want to from here, fire up your rails app and make sure everything is kosher.
#: ruby script/server
(You can, of course, navigate from here to http://localhost:3000/ and get the rails start page if everything is good).
Alright, from here we’re going to start adding our RESTful routes to our rails application by editing config/routes.rb
Opening routes.rb let’s navigate down to the block below:
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
Let’s insert the following simple route right underneath the previous code:
map.resources :users
Save the file and let’s fire up the console:
#: ruby script/console
To test our route on the command line, the first thing we need to do is include the ActionController::UrlWriter module:
>> include ActionController::UrlWriter
And from here all of our route helpers (*_path and *_url) are available from the console.
>> users_path
=> “/users”
>> new_user_path
=> “/user/new”
>> edit_user_path(:id => 1)
=> `”/user/1/edit”
Notice here that even though we don’t have a user with an id of 1 (or a User model, controller, or anything user related), Rails will still happily generate a route for us. All of the route generation faculties available from within rails are now available for you to test on the console, which will hopefully save you some of the hair we lost during our debugging session.
1 comment so far ↓
You can use the ActionController::Integration::Session object that is available at the console with the name “app”:
>> app.users_path
=> "/users"
Which is even better, because when you include ActionController::UrlWriter you aren’t defining the host name, so you can’t use route helpers that points to absolute URLs until you define it at default_url_options[:host]:
>> users_url
RuntimeError: Missing host to link to! Please provide :host parameter or set default_url_options[:host]
>> default_url_options[:host] = “example.com”
=> “example.com”
webapp:development> users_url
=> “http://example.com/users”
With the app object, the host name is automatically prepopulated to “www.example.com”:
>> app.host
=> "www.example.com"
>> app.users_url
=> "http://www.example.com/users"
Leave a Comment