Your browser (Internet Explorer 6) is out of date. It has known security flaws and may not display all features of this and other websites. Learn how to update your browser.
X

Ruby on Rails 3 RESTful and default routes

You have probably created some action in your controller class and can’t access it right? Well you need to have some default routing rules set up in order for rails to understand the url and route it to the appropriate action and controller. This will happen alot with AJAX calls where you simply want to go to an action with no ID. Or maybe you want to go to an action but supply a bunch of parameters without an ID.

class HomeController < ApplicationController
 
  def dothisaction
   # do some stuff
  end
end

Assuming you have defined the home controller as a RESTful controller by adding to your routes.rb

resources :home

In your webbrowser:

localhost/home/dothisaction

You get:

Started GET "/home/foo"
 
AbstractController::ActionNotFound (The action 'show' could not be found for HomeController):

What is happening? Rails is matching the RESTful rule:

home GET    /home/:id(.:format)                    {:controller=>"home", :action=>"show"}

to this URL request. We obviously don’t want that.

So if you want this controller to be RESTful, you must manually add each non RESTful route to your routes.rb like so:

match 'home/dothisaction' => "home#dothisaction"  #Must be before 'resources :home' line to take precedence 
resources :home

Or you can remove the “resources :home” line in the routes.rb and you can add (or uncomment)

match ':controller(/:action(/:id(.:format)))'

This line will automap any action method you have defined in a controller to a url. The parenthesis indicate that the argument is optional. So the url:

localhost/home/dothisaction/5.pdf
 
will map the parameters:
 
:action => "dothisaction"
:id => 5
:format => "pdf"

Leaving off the :id and :format parameters will work just as well.

Be aware that routing precedence is defined by the order the rules appear in routes.rb.

Leave a comment  

name*

email*

website

Submit comment