1
2

More than 3 years have passed since last update.

rail チートシート ルーティング編

Posted at

ルーティングについて一括で見れるチートシートが欲しいので
作ることにしました。

基本

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
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2