Splitting Routes File Into Multiple Files

前端 未结 4 1557

I\'m working w/ a Rails 3 application and I want to split up the routes into separate files depending on the subdomain. Right now I have this in my routes.rb file:



        
相关标签:
4条回答
  • 2020-12-18 21:37

    We used this in our app:

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

    If you try to access config.paths['config/routes'] normally, it returns the relative path to config/routes.rb, so by doing the above you're giving it relative paths to all of the files in your routes folder and removing the reference to config/routes.rb

    0 讨论(0)
  • 2020-12-18 21:45

    Add the route file to the app route loading path:

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

    Wrap your other route file in a block like this.

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

    Works for me in rails 3.0

    0 讨论(0)
  • 2020-12-18 21:48

    In Rails 3.2, config.paths is now a hash, so @sunkencity's solution can be modified to:

    # config/application.rb
    config.paths["config/routes"] << File.join(Rails.root, "config/routes/fooroutes.rb")
    
    0 讨论(0)
  • 2020-12-18 21:48

    Sunkencity's answer seems to be identical to the following link, but for completeness' sake: https://rails-bestpractices.com/posts/2011/05/04/split-route-namespaces-into-different-files/

    Note that routes defined later will override routes defined earlier. However, if you use something like

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

    you don't know in what order the files will be read. So use

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

    instead, so you at least know they will be in alphabetical order.

    0 讨论(0)
提交回复
热议问题