LoginSignup
1
0

More than 1 year has passed since last update.

【Rails】ルーティングについて

Posted at

はじめに

ルーティングについて学習した内容をまとめました。

ルーティングとは

ルーティングとは、HTTPリクエストとURLを元に、どのコントローラーのどのアクションを実行するか結びつけること。

rootで作成

rootとはドメイン名の後ろに何もついていないトップページのこと。

app/config/routes.rb
root to: 'articles#index’

GET,POST,PATCH,DELETEで作成

各アクションに対して個別でルーティングを指定。

ただし、記述内容が多くなりミスが起きやすくなる。

app/config/routes.rb
Rails.application.routes.draw do
	post "articles"         => "articles#create"   
  get "articles/new"      => "articles#new"   
  get "articles/:id/edit" => "articles#edit"   
  get "articles/:id"      => "articles#show"   
  patch "articles/:id"    => "articles#update"   
  delete "articles/:id"   => "articles#destroy"
end

resourcesで作成

resourcesメソッドでルーティングを作成すると、WebアプリケーションのCRUD機能を実装するために必要なルーティングを全て作成することができる

app/config/routes.rb
resources :articles
$rake routes

     articles GET /articles(.:format)          articles#index 
              POST /articles(.:format)         articles#create 
 new_articles GET /articles/new(.:format)      articles#new 
edit_articles GET /articles/:id/edit(.:format) articles#edit 
     articles GET /articles/:id(.:format)      articles#show 
              PATCH /articles/:id(.:format)    articles#update 
              PUT /articles/:id(.:format)      articles#update 
              DELETE /articles/:id(.:format)   articles#destroy

resourceで作成

resourcesメソッドと異なる点は

 ・indexが定義されない

 ・Pathにidがない

app/config/routes.rb
resource :profile
$rake routes

  new_profile   GET    /profile/new(.:format)   profile#new
 edit_profile   GET    /profile/edit(.:format)  profile#edit
      profile   GET    /profile(.:format)       profile#show
                PATCH  /profile(.:format)       profile#update
                PUT    /profile(.:format)       profile#update
                DELETE /profile(.:format)       profile#destroy
                POST   /profile(.:format)       profile#create
1
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
1
0