user3206458
user3206458

Reputation: 5

Aliasing routes in rails 4

If I have the following routes

resources :pages do
    resources :sections
end

I get routes that look like this:

/pages  = #index
/pages/:id = #show
/pages/:id/edit = #edit
...etc

How can I go about making it so that the url for the #show action of the pages controller looks like '/:id', without the '/pages/' prefix? should I exclude #show from resources :page & create a get route + alias for it separately? or is there a way to do it from inside the resources :page block? Thanks in advanced.

EDIT:

Changed it to:

resources :pages, except: [:show] do
  resources :sections
end

get '/:id', to: 'pages#show'

& rerouting non-existing :ids' to 404 for now, let me know if there's a better solution. Thanks.

Upvotes: 0

Views: 98

Answers (1)

Michał Szajbe
Michał Szajbe

Reputation: 9002

get '/:id', to: 'pages#show', as: 'page'

Make sure this is at the bottom of your routes.rb file, otherwise it is going to hijack requests to other routes.

This also gives you page_url and page_path helper methods. But to use them you must exclude show action from previous routes.

resources :pages, except: [:show]

Upvotes: 2

Related Questions