Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you have to mess with Rails's "routes.rb" file?

I never touch routes.rb beyond calling map.root to set a default route. I've always been content to use URLs of the form...

/controller/action/perhaps_an_id

and it works fine.

Does this make me a bad person? Am I missing out on something totally awesome?

What if I try to adopt RESTful design? Would that mean I have to edit routes.rb or could I continue to pleasantly ignore it?

(I tried to read up on this topic in The Rails Way but it was unbearable.)

like image 996
Ethan Avatar asked Jan 02 '09 20:01

Ethan


People also ask

What is routes RB in Rails?

rb . The Rails router recognises URLs and dispatches them to a controller's action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views. Let's consider an application to book rooms in different Hotels and take a look at how this works.

How do routes work in Rails?

Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.


2 Answers

If you generate your resources with the default scaffolding then it will even include the restful routing for you in routes.rb.

If you're not using the scaffolding then the reason that it's working is because of the default routes at the bottom by default:

    map.connect ':controller/:action/:id'
    map.connect ':controller/:action/:id.:format'

I've been following that it's best practice to remove these for production applications and instead make sure that only the resources that need to be exposed are exposed. With Rails 2.2 you can even limit the RESTful methods from map.resources by:

map.resources :posts, :only => [:index, :show]
map.resources :comments, :except => [:edit]

There's also tons of cool things you can do with nested resources, named routes, etc. They have a lot of examples in the docs (http://www.railsbrain.com/api/rails-2.2.2/doc/index.html?a=M000255&name=resources)

like image 62
Dan McNevin Avatar answered Oct 29 '22 11:10

Dan McNevin


You may also want to make custom named routes for your marketing department (eg: mycoolsite.com/free-trial) that go off to specific controllers and actions, etc.

Ryan Bates has a series of screencasts that go over some of the neat things you can do with routes: http://railscasts.com/tags/14

like image 39
Derek P. Avatar answered Oct 29 '22 10:10

Derek P.