如果我所做的任何假设是错误的,请纠正我,但这是我的想法:
当我们在路由文件中使用新的“资源”时,为了拥有新的 GET REST API,最好还使用新的“ Controller ” “该资源。
现在,当我们使用新 Controller 时,我们还会根据该 Controller 的名称获得新默认路由。 这就是我的问题开始的地方:)
我已经有一个 Controller 和一个 GET REST,例如我有一个 health_mamagment
Controller ,然后是一个类似 /health_managment/id.json
的 URL
现在,当我访问该 URL 时,它还有几个导航链接(例如 Windows 应用程序中的选项卡),因此用户可以单击其他链接并需要查看一些新数据。 (仍然是相同的工作流程,他只是想看到一些新数据)。
因此,我在这里调用一个新的 GET REST API 来获取名为 Payers 的链接的新数据
那么像 /health_managment/id/payes
这样的 URL 有意义吗?
但是,如果我们为这个新的“付款人” View 创建一个新的 Controller 和资源,那么在路由文件中我可以以某种方式使用“as”关键字吗?并将新路线映射为 /health_managment/id/payes
最佳答案
您可以在路由文件中嵌套资源并指定要使用的 Controller :
# /config/routes.rb
resources :health_managment do
resources :payes, :controller => "Payer" do
member do
# Your custom routes
end
end
end
这将导致您可以使用该网址 /health_managment/id/payes
作为对您的“付款人” Controller 的访问。
使用 :as 不会修改 URI 端点,但会修改命名助手,如下所述: http://guides.rubyonrails.org/routing.html在第 4 节。
根据评论中的要求,这里是对“成员”部分的更深入的了解:
# /config/routes.rb
resources :posts do
get 'recent'
member do
get 'abstract'
end
end
将生成自定义网址:
- GET/posts/recent 应该显示帖子列表。您正在将该网址链接到帖子集合
- GET/posts/:id/abstract 应该以另一种方式显示一个帖子(带有指定的 ID)
或者,您也可以这样编写这条路线:
# /config/routes.rb
resources :posts do
get 'recent', :on => :collection
get 'abstract', :on => :member
end
当您声明子资源时,它们被设置在“成员级别”,因此:
# /config/routes.rb
resources :posts do
get 'recent', :on => :collection
get 'abstract', :on => :member
resources :comments do
# Routes again
end
end
将允许您访问 URI/posts/:id/comments 并从那里定义自定义路由
关于ruby-on-rails - 路由文件有多灵活,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15092819/