在 Rails 5 中将大的 routes.rb 分成多个文件 [英] Divide large routes.rb to multiple files in Rails 5

查看:41
本文介绍了在 Rails 5 中将大的 routes.rb 分成多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的 rails 4 应用程序升级到 5.0.0.beta2.目前我通过设置 config.paths["config/routes.rb"]routes.rb 文件分成多个文件,例如,

I want to upgrade my rails 4 app to 5.0.0.beta2. Currently I divided the routes.rb file to multiple files by setting config.paths["config/routes.rb"] e.g.,

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

似乎 rails 5.0.0.beta2 也公开了 config.paths["config/routes.rb"] 但上面的代码不起作用.如何在 rails 5 中分割 routes.rb 文件?

It seems rails 5.0.0.beta2 also exposes config.paths["config/routes.rb"] but the above code doesn't work. How can I divide routes.rb file in rails 5?

推荐答案

Rails 6.1+ 从多个文件加载路由的内置方式.

来自官方Rails 文档:

如果您在一个包含数千个路由的大型应用程序中工作,单个 config/routes.rb 文件可能会变得笨重且难以阅读.

If you work in a large application with thousands of routes, a single config/routes.rb file can become cumbersome and hard to read.

Rails 提供了一种使用 draw 宏将巨大的单个 routes.rb 文件分解为多个小文件的方法.

Rails offers a way to break a gigantic single routes.rb file into multiple small ones using the draw macro.

# config/routes.rb

Rails.application.routes.draw do
  get 'foo', to: 'foo#bar'

  draw(:admin) # Will load another route file located in `config/routes/admin.rb`
end

# config/routes/admin.rb

namespace :admin do
  resources :comments
end

Rails.application.routes.draw 块内部调用 draw(:admin) 将尝试加载与给定参数同名的路由文件(在本例中为 admin.rb).该文件需要位于 config/routes 目录或任何子目录(即 config/routes/admin.rbconfig/routes/external/admin.rb).

Calling draw(:admin) inside the Rails.application.routes.draw block itself will try to load a route file that has the same name as the argument given (admin.rb in this case). The file needs to be located inside the config/routes directory or any sub-directory (i.e. config/routes/admin.rb or config/routes/external/admin.rb).

您可以在 admin.rb 路由文件中使用普通的路由 DSL,但是您不应该像这样用 Rails.application.routes.draw 块包围它你在主 config/routes.rb 文件中做了.

You can use the normal routing DSL inside the admin.rb routing file, however you shouldn't surround it with the Rails.application.routes.draw block like you did in the main config/routes.rb file.

链接到相应的 PR.

这篇关于在 Rails 5 中将大的 routes.rb 分成多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆