Just do IT

思うは招く

Railsでコントローラーは変えずにURIの表示を変える方法

たとえば、/entriesというURIではなくrentalsにしたい場合。

Rails.application.routes.draw do
  resources :entries, only: [:new, :create, :destroy, :index],
    path: :rentals
end

path: :rentalsをつけて、パスだけを変えている。 これでrails routesでルーティングを確認すると

Prefix Verb URI Pattern Controller#Action
entries GET /rentals(.:format) entries#index
entries POST /rentals(.:format) entries#create
new_entry GET /rentals/new(.:format) entries#new
entry DELETE /rentals/:id(.:format) entries#destroy

本来なら、コントローラーのアクション名どおり、/entriesになるはずが、/rentalsになっている。 しかし、コントローラーのアクションは設定したとおりentries#indexなどになっているのがわかる。