gpt4 book ai didi

ruby-on-rails - 是否可以将外部路由文件包含到主 routes.rb 文件中?

转载 作者:数据小太阳 更新时间:2023-10-29 07:55:46 25 4
gpt4 key购买 nike

我有大量的路由,我想将它们分成不同的路由文件。

我创建了一个“routes-secondary.rb”并在那里添加了一些路线。然后我尝试在应用程序的主要 routes.rb 中添加类似这样的内容:

require "#{Rails.root}/config/routes-secondary.rb"

但这不起作用,因为 Rails 无法识别 routes-secondary.rb 中的路由。有没有办法正确地做到这一点?

最佳答案

(我已经更新了这个答案以利用 RouteReloader 进行开发工作)

您可以轻松完成此操作(甚至在 Rails 4 中!)。

配置/路由.rb:

Rails.application.routes.draw do
resources :foo
end

配置/路由/included.rb:

Rails.application.routes.draw do
resources :bar
end

config/initializers/routes.rb

Rails.application.routes_reloader.paths.unshift *Dir[File.expand_path("../../routes/**/*.rb", __FILE__)]

这会将 config/routes 下的所有文件添加到应用程序路由中,并且可能会按文件名的反向词法顺序添加它们。如果你想以不同的顺序加载路由,而不是 glob,你可以按所需的顺序将路由推送或取消移动到 routes_reloader.paths 上。

rake 路:

   Prefix Verb   URI Pattern             Controller#Action
foo_index GET /foo(.:format) foo#index
POST /foo(.:format) foo#create
new_foo GET /foo/new(.:format) foo#new
edit_foo GET /foo/:id/edit(.:format) foo#edit
foo GET /foo/:id(.:format) foo#show
PATCH /foo/:id(.:format) foo#update
PUT /foo/:id(.:format) foo#update
DELETE /foo/:id(.:format) foo#destroy
bar_index GET /bar(.:format) bar#index
POST /bar(.:format) bar#create
new_bar GET /bar/new(.:format) bar#new
edit_bar GET /bar/:id/edit(.:format) bar#edit
bar GET /bar/:id(.:format) bar#show
PATCH /bar/:id(.:format) bar#update
PUT /bar/:id(.:format) bar#update
DELETE /bar/:id(.:format) bar#destroy

关于ruby-on-rails - 是否可以将外部路由文件包含到主 routes.rb 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27258481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com