LoginSignup
8
6

More than 1 year has passed since last update.

【Rails】よく使うルーティングまとめ

Last updated at Posted at 2020-01-30

色々あるので、よく使うやつをまとめました。

config/routes.rb
# 基本
get '/login', to: 'sessions#new'
post   '/login',   to: 'sessions#create'

# root path(トップページ)
root to: 'static_pages#index'

# resources(index, show, new, create, edit, update, destroy)
resources :users

# /:idの代わりに/:hogehogeを使う
resources :users, param: :hogehoge

# resourcesで一部のアクションだけ使う
resources :tasks, only: %i[new create edit update]

# resourcesでアクションを追加
resources :products do
  collection do
    get :sold
  end
end

# resourcesでアクションを追加(editアクションのように、パスにidをつける)
resources :products do
  member do
    get :short
  end
end

# 組み合わせ
resources :pw_resets, only: %i[new create edit update] do
  collection do
    get :complete
  end
end

# 名前空間を分けた場合
namespace :admin do
  root to: 'static_pages#index'
  get '/login', to: 'sessions#new'
.
.
end

# 開発環境だけルーティングを有効化
if Rails.env.development?
  mount LetterOpenerWeb::Engine, at: '/letter_opener'
end
8
6
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
8
6