【问题标题】:Is it possible to include external routes files into the main routes.rb file?是否可以将外部路由文件包含到主 routes.rb 文件中?
【发布时间】:2015-01-31 05:37:41
【问题描述】:

我有大量的路线,我想将它们分成不同的路线文件。

我创建了一个“routes-secondary.rb”并在那里添加了一些路由。然后我尝试在应用程序的主要 routes.rb 中添加类似这样的内容:

需要“#{Rails.root}/config/routes-secondary.rb”

但这不起作用,因为 Rails 无法识别 routes-secondary.rb 中的路由。有没有办法正确地做到这一点?

【问题讨论】:

    标签: ruby-on-rails ruby routing


    【解决方案1】:

    (我已更新此答案以利用 RouteReloader 进行开发工作)

    您可以轻松完成此操作(即使在 Rails 4 中!)。

    config/routes.rb:

    Rails.application.routes.draw do
      resources :foo
    end
    

    config/routes/included.rb:

    Rails.application.routes.draw do
      resources :bar
    end
    

    config/initializers/routes.rb

    Rails.application.routes_reloader.paths.unshift *Dir[File.expand_path("../../routes/**/*.rb", __FILE__)]
    

    这会将 config/routes 下的所有文件添加到应用程序路由中,并且可能会按文件名以相反的词法顺序添加它们。如果您想以不同的顺序加载路由,而不是全局,您可以按所需的顺序将路由推送或取消移动到 routes_reloader.paths。

    耙路线:

       Prefix Verb   URI Pattern             Controller#Action
    foo_index GET    /foo(.:format)          foo#index
              POST   /foo(.:format)          foo#create
      new_foo GET    /foo/new(.:format)      foo#new
     edit_foo GET    /foo/:id/edit(.:format) foo#edit
          foo GET    /foo/:id(.:format)      foo#show
              PATCH  /foo/:id(.:format)      foo#update
              PUT    /foo/:id(.:format)      foo#update
              DELETE /foo/:id(.:format)      foo#destroy
    bar_index GET    /bar(.:format)          bar#index
              POST   /bar(.:format)          bar#create
      new_bar GET    /bar/new(.:format)      bar#new
     edit_bar GET    /bar/:id/edit(.:format) bar#edit
          bar GET    /bar/:id(.:format)      bar#show
              PATCH  /bar/:id(.:format)      bar#update
              PUT    /bar/:id(.:format)      bar#update
              DELETE /bar/:id(.:format)      bar#destroy
    

    【讨论】:

    • 这看起来很棒。谢谢克里斯。外部路由按预期工作。我遇到的一个问题是,如果我以任何方式修改主 routes.rb 文件(例如添加注释甚至空格),外部文件中的路由将停止工作,这迫使我重新启动应用程序。你知道是什么导致了这个问题吗?
    • 我会怀疑 Rails 4 中的路由重载机制。我没有遇到过这种情况,因为自从使用 Rails 4 以来我的路由大多是静态的。给我一些看看我能不能得到我脑子里想着它在做什么。
    • @sjsc 查看我的编辑;将额外的路由文件修补到路由重新加载器中,这使得它在开发中按预期工作。这与引擎用于将其路由添加到应用程序的机制相同。
    • 谢谢克里斯。我通过添加上面的 unshift 行进行了尝试,但出现此错误:“RuntimeError: can't modify frozen Array”
    • 您是否在初始化程序中修改这些路由?我的测试用例肯定是在使用 4.1.8 的股票应用程序。不过,它们可能会在初始化后冻结。
    【解决方案2】:

    如果您使用的是 Rails 4,则无法直接执行此操作,here 对此进行了解释。在 rails 3 中,您可以按照 here 的说明修改 config.paths 哈希。

    【讨论】:

    • 啊,我明白了。谢谢迈克。不幸的是,我正在使用 Rails 4
    猜你喜欢
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    • 2020-12-21
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多