Rails 3 : route a resource to another name

我的梦境 提交于 2019-12-21 03:14:16

问题


I have a CRUD controller for a model.

Doing resources :foo allows me to route on /foo/:id, etc. for calling actions.

I want add a route for a translation of 'foo' in another language. Let's say 'toto'. So I want all the /toto/:id, etc., routes to act exactly like the /foo/:id, etc., routes.

How may I achieve that?


回答1:


You can add a new resource and specify foo as the controller:

resources :toto, :controller=>"foo"

This will point all the actions to "foo", but there is a gotcha. I think you will run into problems with the links on the page, if you are using foo_url or something like that. So you would have to figure out a way to create the URLs dymanically based on the controller in "request.path".




回答2:


This will let you rename paths seen by the user but keep the original name of your controllers in the code:

scope(:path_names => { :new => "neu", :edit => "bearbeiten" }) do
  resources :categories, :path => "kategorien"
end

From the Ruby on Rails Guides




回答3:


If I understand you correctly, you want to just use another path.

resources :foo, path: 'toto'

Now you will have:

GET /toto          foo#index
GET /toto/:id      foo#show
...



回答4:


You can achieve something close to this using scope:

scope ':language/' do
  resources :foo, controller: 'bar_controller'
end

This make your bar_controller a resource to anything/foo, where anything gets passed as the :language parameter.

so:

  • en_US/foo
  • de_DE/foo
  • ja_JP/foo

all get handled by bar_controller, with the normal resource mapping, and you get params[:language] in the controller for free.



来源:https://stackoverflow.com/questions/3675013/rails-3-route-a-resource-to-another-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!