ルーティングについて
久々にRailsを触ったら色々忘れていたので過去にメモしていたものと合わせて基本的なルーティングのおさらいです。
目次
rake routes(rails routes)
設定されているルーティングを確認するコマンド。 これを書くために調べていて知ったのですが、現在がrakeがrailsに置き換えられていっているそうなのでrails routesを使う方が良い模様。 とりあえずこのコマンドでルートの確認をする。
$ rake routes
もしくは
$ rails routes
http://localhost:3000/rails/info/
にアクセスしても一覧が見れる。この方が見やすい。
※rails sでサーバーに接続している状態の時に限ります
※URL的にはhttp://localhost:3000/rails/info/routes
が正しいのですが上記のURLにアクセスしても自動的に同じページが表示されます。
ルーティングの設定(基本)
📁config/routes.rb
Rails.application.routes.draw do この中に記述 end
Rails.application.routes.draw do root "contents#index" get "contents/new" => "tweets#new" post "contents" => "tweets#create" end
《root》サイトトップのページを指定
以上のように記述している場合
http://localhost:3000
にアクセスするとcontentsアクションのindexメソッドが実行。
/coutents/new
にアクセスすると、contentsアクションのnewメソッドが実行。
/coutents/create
だとcontentsアクションのcreateメソッドが実行。
※ビューはそれらに対応したファイルが表示される。
/contents/new
にアクセス→/app/views/contents/new.html.erb
など
resources
先のように記述していくと、記述量が増え管理が大変なためresourcesを使ったルーティングが推奨されている模様。 resourcesを使うと7つのルーティングが一括で生成されます。 必要なルーテイングのみを指定することも可。(必要のないアクションを指定することもできる。)
📁config/routes.rb
Rails.application.routes.draw do resources :contents resources :users, only: [:index, :show] end
contentsアクション→7つ全て一括生成 usersアクション→indexとshowのみ生成
$ rake routes Prefix Verb URI Pattern Controller#Action contents GET /contents(.:format) contents#index POST /contents(.:format) contents#create new_content GET /contents/new(.:format) contents#new edit_content GET /contents/:id/edit(.:format) contents#edit content GET /contents/:id(.:format) contents#show PATCH /contents/:id(.:format) contents#update PUT /contents/:id(.:format) contents#update DELETE /contents/:id(.:format) contents#destroy users GET /users(.:format) users#index user GET /users/:id(.:format) users#show
resource
resourcesと同じに見えますが複数形か単数形か、です。 これらふたつには明確な違いがあります。 - indexアクションが含まれない - URI Patternにidを含まない 以上の2点です。
Rails.application.routes.draw do resource :users end
$ rake routes Prefix Verb URI Pattern Controller#Action POST /users(.:format) users#create new_user GET /users/new(.:format) users#new edit_user GET /users/edit(.:format) users#edit user GET /users/(.:format) users#show PATCH /users/(.:format) users#update PUT /users/(.:format) users#update DELETE /users/(.:format) users#destroy
もちろんもっと書き方があるし、私自身使っているので今後まとめたい。