Splitting Routes File Into Multiple Files

末鹿安然 提交于 2019-12-18 05:40:15

问题


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:

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

And In my routes/api.rb file I have:

resources :skateparks

This doesn't seem to work though because if I run rake routes I get

undefined method `resources' for main:Object

Also, if I try to navigate to http://0.0.0.0:3000/ I get:

Routing Error

No route matches "/"

回答1:


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")



回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/7303660/splitting-routes-file-into-multiple-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!