Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

routing - How to remove controller names from rails routes?

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?

question from:https://stackoverflow.com/questions/6369476/how-to-remove-controller-names-from-rails-routes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way you are doing it should work. I don't know what problem you are experiencing but if you copied the example code from your app directly then it might be because of the extra end that you have put in your routes. It should probably look like this:

resource :users, :path => '' do
  resource :questions, :path => ''
end

Another thing that could be the cause and that you need to be vary careful about is that these routes pretty much catches all requests and you should have them last in your routes.rb so that other routes matches first. Take this scenario for example:

resource :users, :path => '' do
  resource :questions, :path => ''
end

resources :posts

If you do it this way then no request will ever be routed to the Posts controller since a request to /posts/1 will be sent to the Questions controller with :user_id => 'posts', :id => 1

Edit:

Also, I now noticed that you use resource instead of resources. Don't know if that is intended or if it is a mistake.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...