routes.rbとルーティング
routes.rb
Rails.application.routes.draw do
resources :records
root 'records#index'
end
例えば上のようにrecordsモデルに対してルーティングを設定した場合、rails routesの実行すると以下
Prefix Verb URI Pattern Controller#Action
records GET /records(.:format) records#index
POST /records(.:format) records#create
new_record GET /records/new(.:format) records#new
edit_record GET /records/:id/edit(.:format) records#edit
record GET /records/:id(.:format) records#show
PATCH /records/:id(.:format) records#update
PUT /records/:id(.:format) records#update
DELETE /records/:id(.:format) records#destroy
root GET / records#index
ページを追加する
新しいHTMLページを追加しようとしてroutes.rbを編集した
routes.rb
Rails.application.routes.draw do
resources :records
get "records/all" => "records#all"
root 'records#index'
end
ルーティングテーブルの下から二行目に追加された
Prefix Verb URI Pattern Controller#Action
records GET /records(.:format) records#index
POST /records(.:format) records#create
new_record GET /records/new(.:format) records#new
edit_record GET /records/:id/edit(.:format) records#edit
record GET /records/:id(.:format) records#show
PATCH /records/:id(.:format) records#update
PUT /records/:id(.:format) records#update
DELETE /records/:id(.:format) records#destroy
records_all GET /records/all(.:format) records#all
root GET / records#index
しかしこの状態で/records/allにアクセスすると「コントローラにshowメソッドが存在しません」のエラー
showメソッドなんて呼んでないのに・・・
#解決策
routes.rb
Rails.application.routes.draw do
get "records/all" => "records#all"
resources :records
root 'records#index'
end
すごく単純にroutes.rbでの順番を入れ替えるだけ
Prefix Verb URI Pattern Controller#Action
records_all GET /records/all(.:format) records#all
records GET /records(.:format) records#index
POST /records(.:format) records#create
new_record GET /records/new(.:format) records#new
edit_record GET /records/:id/edit(.:format) records#edit
record GET /records/:id(.:format) records#show
PATCH /records/:id(.:format) records#update
PUT /records/:id(.:format) records#update
DELETE /records/:id(.:format) records#destroy
root GET / records#index
もともとルーティングテーブルは上から読んでいくので、/records/allの設定が/records/:idより後ろにあると先に/records/:idに引っかかり、showメソッドを呼び出そうとしてしまう