我想将我的rails 4 app升级到5.0.0.beta2.目前我routes.rb通过设置config.paths["config/routes.rb"]例如,将文件分成多个文件,
module MyApp
class Application < Rails::Application
config.paths["config/routes.rb"]
.concat(Dir[Rails.root.join("config/routes/*.rb")])
end
end
Run Code Online (Sandbox Code Playgroud)
似乎rails 5.0.0.beta2也暴露config.paths["config/routes.rb"]但上面的代码不起作用.如何routes.rb在rails 5中分割文件?
Mar*_*n13 10
如果您在具有数千条路由的大型应用程序中工作,则单个config/routes.rb文件可能会变得笨重且难以阅读。
Rails 提供了一种routes.rb使用 draw 宏将巨大的单个文件分解为多个小文件的方法。
# config/routes.rb
Rails.application.routes.draw do
get 'foo', to: 'foo#bar'
draw(:admin) # Will load another route file located in `config/routes/admin.rb`
end
# config/routes/admin.rb
namespace :admin do
resources :comments
end
Run Code Online (Sandbox Code Playgroud)
draw(:admin)在Rails.application.routes.draw块内部调用将尝试加载与给定参数同名的路由文件(admin.rb在本例中)。该文件需要位于config/routes目录或任何子目录(即config/routes/admin.rb或config/routes/external/admin.rb)内。
您可以在admin.rb路由文件中使用普通的路由 DSL ,但是您不应该Rails.application.routes.draw像在主config/routes.rb文件中那样用块包围它。
小智 7
你可以在config/application.rb中编写一些代码
config.paths ['config/routes.rb'].concat Dir [Rails.root.join("config/routes/*.rb")]
这是一篇很好的文章,简单,简洁,直截了当 - 不是我的.
配置/ application.rb中
Run Code Online (Sandbox Code Playgroud)module YourProject class Application < Rails::Application config.autoload_paths += %W(#{config.root}/config/routes) end end配置/路由/ admin_routes.rb
Run Code Online (Sandbox Code Playgroud)module AdminRoutes def self.extended(router) router.instance_exec do namespace :admin do resources :articles root to: "dashboard#index" end end end end配置/ routes.rb中
Run Code Online (Sandbox Code Playgroud)Rails.application.routes.draw do extend AdminRoutes # A lot of routes end
class ActionDispatch::Routing::Mapper
def draw(routes_name)
instance_eval(File.read(Rails.root.join("config/routes/#{routes_name}.rb")))
end
end
BCX::Application.routes.draw do
draw :api
draw :account
draw :session
draw :people_and_groups
draw :projects
draw :calendars
draw :legacy_slugs
draw :ensembles_and_buckets
draw :globals
draw :monitoring
draw :mail_attachments
draw :message_preview
draw :misc
root to: 'projects#index'
end
Run Code Online (Sandbox Code Playgroud)