Override “show” resource route in Rails

2019-01-27 22:28发布

问题:

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