0
0

【Rails】resourcesによるルーティング

Posted at

はじめに

Rails初学者の学習内容の備忘録です。
間違いや補足等あればご指摘いただけると幸いです。

今回はresourcesについて学習したのでまとめます。

resourcesとは?

Railsのルーティングでよく使われるメソッドで、一般的なCRUD(Create,Read,Update,Delete)操作に対応するルートを自動生成します。

resourcesを使わない場合

routes.rb
 get "posts", to: "posts#index"
 get "posts/new", to: "posts#new"
 get "posts/:id", to: "posts#show"
 post "posts", to: "posts#create"
 get "posts/:id/edit", to: "posts#edit"
 patch "posts/:id", to: "posts#update"
 delete "posts/:id", to: "posts#destroy"

resourcesを使わない場合は、上記のように書く必要がありますが

resourcesを使った場合

routes.rb
  resources :post

resourcesを使うと7つのアクションを1行で書くことができます。
よく使う基本的なやつは1行で書いちゃおうぜということですね。

resourcesの使い方

使い方はroutes.rbの中で

routes.rb
  resources :コントローラ名

とするだけです。また、

routes.rb
  resources :コントローラ名, :コントローラ名

として複数のコントローラのルーティングを定義することも可能です。

onlyとexcept
特定のアクションのみを定義したい場合

routes.rb
  resources :post, only: {:index, :show}

とすれば、indexアクションとshowアクションのみ定義されます。
逆に、特定のアクションを含めたくない場合は、

routes.rb
  resources :post, except: {:index, :show}

とすれば、index、show以外のアクションが定義されます。

まとめ

resourcesを使うことで、RESTfulなコードを効率的に設定でき、可読性も上がる。

参考サイト
Pikawaka 【Rails】 resourcesメソッドを使ってルーティングを定義しよう!

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