Search code examples
ruby-on-railsruby-on-rails-4rails-routing

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?


Solution

  • 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