How to remove controller names from rails routes?

Viewed 11732

I would like to trim down the routes on my application so that:

http://myapplication.com/users/peter/questions/how-do-i-create-urls

becomes...

http://myapplication.com/peter/how-do-i-create-urls

I have a users controller and would like it to be resourceful. Users also have a nested resource called questions.

Basic routes file

Without any URL trimming, the routes file looks like this:

...
resources :users do
  resources :questions
end

However the URLs from this take the form of

http://myapplication.com/users/peter/questions/how-do-i-create-urls

rather than

http://myapplication.com/peter/how-do-i-create-urls

Partial success I have tried doing the following:

...
resources :users, :path => '' do
  resources :questions
end

This works and produces:

http://myapplication.com/peter/questions/how-do-i-create-urls

However if I try:

...
resources :users, :path => '' do
  resources :questions, :path => ''
end

Then things start to go wrong.

Is this the right approach and if so, can it be made to work with nested resources too?

4 Answers

Just thought I'd add another possible solution, in case anybody else arrives from Google at a later date.

After looking at this nested resource article, this could be a cleaner solution with almost the same flexibility in routes:

resources :users, :path => ''
resources :users, :path => '', :only => [] do
  resources :questions, :path => '', :except => [:index]

Basically, by including the second parent block, the child resources aren't yielded before the parent resources.

This particular example also assumes that having complete routes for the parent block is more crucial than those for the child. Consequently, the child block is limited from having an index, but this might be acceptable, depending on the situation.

Related