【问题标题】:Splitting Routes File Into Multiple Files将路由文件拆分为多个文件
【发布时间】:2011-11-10 08:17:54
【问题描述】:

我正在使用 Rails 3 应用程序,我想根据子域将路由拆分为单独的文件。现在我的 routes.rb 文件中有这个:

Skateparks::Application.routes.draw do
  constraints(:subdomain => 'api') do
    load 'routes/api.rb'
  end
end

在我的 routes/api.rb 文件中我有:

resources :skateparks

这似乎不起作用,因为如果我运行 rake routes 我会得到 ​​p>

undefined method `resources' for main:Object

另外,如果我尝试导航到 http://0.0.0.0:3000/,我会得到:

路由错误

No route matches "/"

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 routing


    【解决方案1】:

    在 Rails 3.2 中,config.paths 现在是一个哈希,所以@sunkencity 的解决方案可以修改为:

    # config/application.rb
    config.paths["config/routes"] << File.join(Rails.root, "config/routes/fooroutes.rb")
    

    【讨论】:

    • 谢谢!我们在该目录中有多个文件;这很好用:config.paths["config/routes"] += Dir[Rails.root.join("config/routes/*.rb")]
    • 如果你加上Dir[…].sort,我相信你可以信赖这个排序。
    【解决方案2】:

    Sunkencity 的回答似乎与以下链接相同,但为了完整起见:https://rails-bestpractices.com/posts/2011/05/04/split-route-namespaces-into-different-files/

    请注意,稍后定义的路由将覆盖之前定义的路由。但是,如果您使用类似

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

    您不知道读取文件的顺序。所以使用

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

    相反,因此您至少知道它们将按字母顺序排列。

    【讨论】:

      【解决方案3】:

      将路由文件添加到app路由加载路径:

      # config/application.rb
      config.paths.config.routes << File.join(Rails.root, "config/routes/fooroutes.rb")
      

      将您的其他路由文件包装在这样的块中。

      #config/routes/fooroutes.rb
      Rails.application.routes.draw do |map|
        match 'FOO' => 'foo/bar'
      end
      

      在 Rails 3.0 中为我工作

      【讨论】:

      • 删除了对引擎的建议,并添加了配置路由。应该工作!
      • 我使用 config.paths.config.routes 得到 #<:paths::root:0x007fc3fdd1e7a0>undefined method config'
      • 我也一样。有谁知道如何解决这个问题?
      • 不适用于 Rails 3.2,但请参阅 Sam Gibson's answer
      【解决方案4】:

      我们在我们的应用中使用了这个:

          config.paths['config/routes'] = Dir["config/routes/*.rb"]
      

      如果您尝试正常访问config.paths['config/routes'],它将返回到config/routes.rb 的相对路径,因此通过执行上述操作,您将为其提供路由文件夹中所有文件的相对路径并删除对@ 的引用987654324@

      【讨论】:

        猜你喜欢
        • 2018-03-05
        • 1970-01-01
        • 2017-08-15
        • 2013-08-24
        • 1970-01-01
        • 2018-06-24
        • 2014-12-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多