【问题标题】:How to split routes.rb into smaller files如何将 routes.rb 拆分为更小的文件
【发布时间】:2012-02-13 00:15:38
【问题描述】:

是否可以拆分 Rails 3.X routes.rb 文件?

我们有这么多资源,很难找到它们。我想至少拆分 APP 和 REST API 路由。

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    你可以这样做:

    routes.rb

    require 'application_routes'
    require 'rest_api_routes'
    

    lib/application_routes.rb

    YourApplication::Application.routes.draw do
      # Application related routes
    end
    

    lib/rest_api_routes.rb

    YourApplication::Application.routes.draw do
      # REST API related routes
    end
    

    更新:(此方法已从 Rails 中删除)

    Rails edge 新增了一个很棒的多路径文件:

    # config/routes.rb
    draw :admin
    
    # config/routes/admin.rb
    namespace :admin do
      resources :posts
    end
    

    这对于分解大型应用程序中的复杂路由文件非常方便。

    【讨论】:

    【解决方案2】:

    在 Rails3 中,您可以在 config/application.rb 中设置配置

    config.paths.config.routes.concat Dir[Rails.root.join("config/routes/*.rb")]
    

    【讨论】:

    • 这对我来说效果更好,而不是需要 routes.rb 中的文件
    • 这种方法的路线顺序是什么?
    • @Robin 我在我的 OS X 开发机器上试验了我们的应用程序。我将数字放在文件名前面,“1_routes.rb”中的路线在“2_routes.rb”之前,但在我将“1”更改为“3”之后。但它seems 的顺序并不能保证Dir.entries 的顺序,所以你可能需要Dir[…].sort 来依赖它。
    • 不应该是config.paths["config/routes"]吗?您的代码引发未定义的方法错误。
    【解决方案3】:

    Rails 3.2.11

    config.paths["config/routes"].concat Dir[Rails.root.join("config/routes/*.rb")]

    【讨论】:

      猜你喜欢
      • 2013-09-21
      • 1970-01-01
      • 2010-11-13
      • 2017-12-07
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多