ルーティングについて一括で見れるチートシートが欲しいので
作ることにしました。
基本
config/routes
Rails.application.routes.draw do
get 'homes' => 'home#index'
get 'homes/new' => 'home#new'
post 'homes' => 'home#create'
end
ルート
config/routes
Rails.application.routes.draw do
root 'homes#index'
end
resourcesメソッド
config/routes
Rails.application.routes.draw do
resources :items #items_controllerに対してのresourcesメソッド
resources :users, only: [:show] #users_controllerに対してのresourcesメソッド
end
ネストした場合
config/routes
Rails.application.routes.draw do
resources :items do
resources :comments, only: [:create]
end
end
memberメソッドとcollectionメソッド
どちらもresourcesでは自動で生成されないactionへのroutingを設定するのに使用
(pointとかbookなど独自アクションを使用したい時)
二つのメソッドの違いはidが生成されるかされないか。
memberメソッド
自動でidを付加して生成される
Rails.application.routes.draw do
resources :users do
member do
get :point
end
end
end
point_user GET /users/:id/follow(.:format) users#point
collectionメソッド
idわ付加されず生成される
Rails.application.routes.draw do
resources :users do
collection do
get :home
end
end
end
home_users GET /users/slide(.:format) users#point