LoginSignup
0
0

More than 3 years have passed since last update.

【知識用】Railsのルーティングを極める【基本と応用】

Last updated at Posted at 2020-08-29

基本編

7つのアクションはresourcesで

routes.rb
Rails.application.routes.draw do
  resources :notes
end

限定したいときはonlyとexceptを使う

routes.rb
Rails.application.routes.draw do
  resources :notes, only: [:index, :show]
end
routes.rb
Rails.application.routes.draw do
  resources :tweets, except: [:new, :create, :edit, :update, :destroy]
end

onlyはホワイトリスト系
exceptはブラックリスト系

users/1/notesとしたいときはネスト

routes.rb
Rails.application.routes.draw do
  resources :users do
    resources :notes
  end
end

7つのアクション以外は次の2通り

routes.rb
Rails.application.routes.draw do
  resources :notes do
    member do
      get 'review'
    end
  end
end
routes.rb
Rails.application.routes.draw do
  resources :notes do
    collection do
      get 'search'
    end
  end
end

memberはidで指定した特定のリソースに対するアクション
collectionは全体のリソースに対するアクション
をそれぞれ定義する。

応用編

単純なページならresourceで

routes.rb
Rails.application.routes.draw do
  resource :notes
end

これはindexアクションとidが必要ないときに有効。

パスをグループ化したいときはnamespaceを使う

routes.rb
Rails.application.routes.draw do
  namespace :admin do
    resources :users
  end
end

ルートパスの指定方法はrootで

routes.rb
Rails.application.routes.draw do
  root 'notes#index'
end

まとめ

以上Railsのルーティングのまとめでした。
たったこれだけなんですね!

もう少し単純にまとめられそうに思いました。

あとは機能別にまとめていくのもいいかもしれないと思いました。
例えば商品出品機能とか。
基本の型を作る感じ。

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