1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Railsの resources が超便利!ルーティングが一行で完結!

Posted at

Railsでルーティングを定義するとき、get や post を何行も書いていませんか?

# route.rb
get '/children', to: 'children#index'
get '/children/new', to: 'children#new'
post '/children', to: 'children#create'
get '/children/:id', to: 'children#show'
get '/children/:id/edit', to: 'children#edit'
patch '/children/:id', to: 'children#update'
delete '/children/:id', to: 'children#destroy'

これ、全部まとめてたった1行で定義できる方法があるんです。

🎯 resources を使えば一発!

Railsでは resources を使えば、7つの基本的なルーティングが自動で定義されます。

# route.rb
resources :children

これだけでOK。内部的には以下のルーティングが生成されます:

HTTPメソッド パス コントローラー#アクション
GET /children children#index
GET /children/new children#new
POST /children children#create
GET /children/:id children#show
GET /children/:id/edit children#edit
PATCH /children/:id children#update
DELETE /children/:id children#destroy

つまり、index・show・new・create・edit・update・destroyという基本的なアクションはすべて自動生成されます!

💡 link_to も一発で書ける

ルーティングが決まっていれば、link_to などのヘルパーメソッドもすごくシンプルになります。

# ◯◯◯◯.html.erb
<%= link_to '一覧へ', children_path %>
<%= link_to '詳細へ', child_path(@child) %>
<%= link_to '新規作成', new_child_path %>
<%= link_to '編集', edit_child_path(@child) %>
<%= link_to '削除', child_path(child), data: { turbo_method: :delete, turbo_confirm: '本当に削除しますか?' } %>

わざわざURLやアクションを自分で指定する必要はありません。Railsが全部やってくれます。

✂️ 一部だけ使いたいときは?

例えば「index と show だけ使いたい」など、限定したい場合は only オプションが使えます:

# route.rb
resources :children, only: [:index, :show]

逆に destroy だけ除きたい場合は except で:

# route.rb
resources :children, except: [:destroy]

🔁 コントローラー側との連動も楽に

resources によって自動的にURLとアクションが結びつくため、ChildrenController 側では対応するアクション(例:index, show など)を用意するだけでOK。ルーティングとコントローラーの対応関係が分かりやすいのも大きなメリットです。

✅ まとめ

コードが短い

→ルーティングが1行で済む

ミスが減る

→明示的なURLやHTTPメソッドの指定が不要

メンテが楽

→アクションを追加してもルーティングは変更不要

Railsらしい

→RESTful設計に自然と沿える

🏁 おわりに

Railsの resources をうまく使うことで、アプリ全体の構造がすっきりし、開発スピードもグッと上がります。初心者の方こそ、最初から resources の書き方に慣れておくと、後々チーム開発や拡張でも役立ちます!

普段の勉強記録や日々の学びはこちらのはてなブログで投稿しています。
技術の基礎から実践まで、わかりやすくまとめているのでぜひチェックしてみてください!

▶︎はてなブログ:育児パパエンジニアの勉強記録
https://taaa-0991.hatenablog.com/

ご質問・ご指摘があれば、コメントやXでお気軽にどうぞ!
👉[@taaa_099]( https://x.com/taaa_099 )

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?