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 :homeIn 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
[...] This post was mentioned on Twitter by Ruby Brasil and Igor Lanes , Allen Walker. Allen Walker said: Understanding confusing routing issues in ruby on rails 3 http://www.railswizard.com/2011/01/22/ruby-on-rails-3-restful-and-default-routes/ [...]
Tweets that mention Ruby on Rails 3 RESTful and default routes « Rails Wizard -- Topsy.com
January 25, 2011
Thanks for the post. I’m working from an older book and couldn’t even get my Hello World working!
John Natoli
August 15, 2011
its works.. thanks for the post !!!!!!!!
Mani
August 31, 2011