Override “show” resource route in Rails

╄→尐↘猪︶ㄣ 提交于 2019-11-28 07:21:14

问题


resources :some_resource

That is, there is a route /some_resource/:id

In fact, :id for some_resource will always be stored in session, so I want to override the path /some_resource/:id with /some_resource/my. Or I want to override it with /some_resource/ and remove the path GET /some_resource/ for index action.

How can I reach these two goals?


回答1:


In your routes.rb put:

get "some_resource" => "some_resource#show"

before the line

resources :some_resource

Then rails will pick up your "get" before it finds the resources... thus overriding the get /some_resource

In addition, you should specify:

resources :some_resource, :except => :index

although, as mentioned, rails won't pick it up, it is a good practice




回答2:


Chen's answer works fine (and I used that approach for some time), but there is a standardized way. In the Official Rails Guides the use of collection routes is preferred.

Collection routes exist so that Rails won't assume you are specifying a resource :id. In my opinion this is better than overriding a route using precedence within the routes.rb file.

resources :some_resource, :except => :index do
  get 'some_resource', :on => :collection, :action => 'show'
end

If you need to specify more than collection route, then the use of the block is preferred.

resources :some_resource, :except => :index do
  collection do
    get 'some_resource', :action => 'show'
    # more actions...
  end
end


来源:https://stackoverflow.com/questions/12235718/override-show-resource-route-in-rails

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