0
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ルーティングにおける名前空間とリソースの使い分け

Posted at

はじめに

こんにちは、tagokoroです。初心者ながら最近は開発案件に携わっているのですが、急遽使用技術が変わることになり全く触ったことのないRuby,Railsで開発することになりました。まだ体型的な勉強が積めていない中でタスクが降ってきているので、わからなかったことを備忘録として残していこうと思います

今回起きたこと

/service/hoge/fugaのAPIを実装していて、config/routes.rbにこれをルーティングさせようとしていました。このAPIのエンドポイントは以下の構成で定義されています。

  • service: サービス単位のグルーピング(ものレポ構成での区切り)
  • hoge: service内の機能的な区分
  • fuga: 実際にREST的に操作するリソース

このような背景のもと、以下のように実装しました。

namespace :service do
  resources :hoge do
    resources :fuga, only: %i[index]
  end
end

しかしこの定義では以下のような意図しないルーティングが生成されてしまいます。

GET /service/hoge/:hoge_id/fuga  fuga#index

つまり、Railsが hoge をIDを持つリソースとして認識してしまい、:hoge_id がURLに含まれる形になってしまったのです。

resourcesの役割

resoucesを使うと、railsは対象をIDを持つRESTfulなリソースとみなし、以下のアクションのルーティングを自動で生成します。

  • index
  • show
  • update
  • destory
  • create
  • new
  • edit

namespaceの役割

namespaceを使うと、ルーティング上ではURLパスの接頭辞となります。

改善方法

今回のケースでhogeはIDを持つリソースではなく、構想上のグループ化(名前空間)を意味しています。
そのため以下のようにnamespaceを使うのが適切です

namespace :service do
  namespace :hoge do
    resources :fuga, only: %i[index]
  end
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?