简体   繁体   中英

rails routing, add path name also keep old urls working

in my routes file, when i change

resources :foobar

to

resources :foobars, path: "foo-bars"

the urls become example.com/foo-bars , example.com/foo-bars/1 etc. this is ok.

but how can i also keep the old urls, example.com/foobars , example.com/foobar/3 also working?

i know, i can hardcode it,

get "foobars", to: 'foobar#index'
get "foobar/:id", to: 'foobar#show'
...   

but is there a clean way to implement this?

Define both of them

resources :foobars, path: "foo-bars"
resources :foobars, path: "foobars"

EDIT:

For custom actions instead of declaring them twice for each path like this,

resources :foobars, path: "foo-bars"
  collection do
    get 'bulk_new'
    patch 'bulk_create'
    get 'bulk_edit'
    patch 'bulk_update'
  end
end

resources :foobars, path: "foobars"
  collection do
    get 'bulk_new'
    patch 'bulk_create'
    get 'bulk_edit'
    patch 'bulk_update'
  end
end

Create common block and pass it to both resource method calls.

common_block  = lambda do
  collection do
    get 'bulk_new'
    patch 'bulk_create'
    get 'bulk_edit'
    patch 'bulk_update'
  end
end

resources :foobars, path: "foo-bars", &common_block
resources :foobars, path: "foobars", &common_block

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM