kurodakazumichi / issues

0 stars 0 forks source link

【Ruby on Rails】Routes #21

Open kurodakazumichi opened 6 years ago

kurodakazumichi commented 6 years ago

config/routes.rbの書き方について

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

  # ここにどんなURLでどこの処理を実行するかのルーティングを記述していく。
end
kurodakazumichi commented 6 years ago

root

/でアクセスした時の設定

root 'posts#index'

rails routesの結果

Prefix Verb URI Pattern Controller#Action
root GET / posts#index
kurodakazumichi commented 6 years ago

resources

基本的なルーティングを一気に定義できる。

resources :posts
Prefix Verb URI Pattern Controller#Action Description
posts GET /posts(.:format) posts#index 一覧
POST /posts(.:format) posts#create 作成(実行)
new_post GET /posts/new(.:format) posts#new 作成(ページ)
edit_post GET /posts/:id/edit(.:format) posts#edit 編集
post GET /posts/:id(.:format) posts#show 表示
PATCH /posts/:id(.:format) posts#update 更新
PUT /posts/:id(.:format) posts#update 更新
DELETE /posts/:id(.:format) posts#destroy 削除
kurodakazumichi commented 6 years ago

投稿に紐づくコメントのようなケース

投稿ID = 1 に紐ずくコメント一覧だったりはこんな感じで設定する。

resources :posts do
  resources :comments
end
Prefix Verb URI Pattern Controller#Action Description
post_comments GET /posts/:post_id/comments(.:format) comments#index 一覧
edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) comments#edit 編集
post_comment GET /posts/:post_id/comments/:id(.:format) comments#show 表示
PATCH /posts/:post_id/comments/:id(.:format) comments#update 更新
PUT /posts/:post_id/comments/:id(.:format) comments#update 更新
DELETE /posts/:post_id/comments/:id(.:format) comments#destroy 削除
new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new 新規

こんなにたくさんいらないよってとき

実際に使うのはcreateとdestroyだけとか

resources :posts do
  resources :comments, only: [:create, :destroy]
end