LoginSignup
120
120

More than 5 years have passed since last update.

Railsのルーティングを読みやすく作っていく

Posted at

Railsアプリケーションのルーティングは、config/routes.rb1ファイルで最初は開発を始めると思います。
ただ、サービスを運用していくとルーティングは膨らみ、メンテナンスコストも馬鹿になりません。
そのため、ルーティングの設定をできるだけメンテナンスしやすく作っておくことでそのコストを下げようという試みです。

Railsのルーティングは、config/routes.rb がルーティングの設定ファイルにデフォルトで指定されています。
ただ、これは変更可能ですし、複数のファイルに分割もできます。
昨今のアプリケーションの用途は、Web、native(iOS、Android)、APIサーバ、と多岐にわたるので、

config/routes.rb
config/routes/api/v1.rb
config/routes/api/v2.rb
config/routes/web.rb
config/routes/admin.rb
...

のように用途や機能に応じてファイルを分割しておくことで、あとから運用していく人がわかりやすくなり、メンテナンスコストを軽減できます。

Rails3の場合は、config/application.rb

module TheApplication
  class Application < Rails::Application
    ...
    config.paths["config/routes"] += Dir[Rails.root.join("config/routes/**/*.rb")]
    ...
  end
end

Rails4の場合は、

module TheApplication
  class Application < Rails::Application
    ...
    config.paths["config/routes.rb"] += Dir[Rails.root.join("config/routes/**/*.rb")]
    ...
  end
end

と設定します。

120
120
1

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
120
120