views:

19

answers:

2

I am a relative beginner at Rails 3 routing and it has now caused me enough pain that I want to figure out the real solution.

A couple of details:

  • I have some semi-restful controllers that contain some methods outside the standard seven new, create, edit, update, destroy, etc.

  • Generally, I want my routes page to map everything to 'controller/action', but perhaps with the rare exception.

  • I am under the impression that having a general mapping like match ':controller/:action' is not recommended for security reasons, even though I prefer to use session data rather than params which are more easily modified.

What's the best way to go about structuring my routes document in an efficient way?

A: 

You just need define all your route. Only what your really need. use resources to generate some automatic route for you with :only or :except option to avoid useless route.

Less you have route in your route.rb and better is it. So define only what your want and not more.

shingara
+1  A: 

you can use this match in routes.rb:

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

or some of its variant like get instead of match, etc.

As routes are resolved from top to bottom then you can use your exceptions (and standard resource routes) above the generic route rule.

As for the security concerns - if you have this generic rule in your routing table then you should protected all non-action methods in controller with private keyword.

There is another problem with generic rule. Compare this rule:

get "foo/show/:id", :to => "foo#show"

with the generic one. The good thing of this explicit rule is the fact that it's never called for /foo/show (without the id part) so you will not be in situation when there is no params[:id] in your action method.

And one last comment on your question: using session for keeping navigation state is not generally a good thing. It depends on your configuration but sessions can be shared between two browser tabs - and then the navigation can get pretty messy. And don't forget the dreadful Back button.

So my opinion is that you really should not use generic route.

pawien
This is excellent Pawien, thank you. Interesting point on the sessions.
sscirrus