如何嵌套收集路线?
我在Rails 3应用程序中使用以下路由配置。
# config/routes.rb MyApp::Application.routes.draw do resources :products do get 'statistics', on: :collection, controller: "statistics", action: "index" end end
StatisticController
有两个简单的方法:
# app/controllers/statistics_controller.rb class StatisticsController < ApplicationController def index @statistics = Statistic.chronologic render json: @statistics end def latest @statistic = Statistic.latest render json: @statistic end end
这将生成由StatisticsController
成功处理的URL /products/statistics
。
如何定义导致以下URL的路由: /products/statistics/latest
?
可选:我尝试将工作定义置于关注点但它失败并显示错误消息:
undefined method 'concern' for #<ActionDispatch::Routing::Mapper ...
我想你可以通过两种方式来做到这一点。
方法1:
resources :products do get 'statistics', on: :collection, controller: "statistics", action: "index" get 'statistics/latest', on: :collection, controller: "statistics", action: "latest" end
方法2,如果products
有许多路线,则应将其用于更好的组织路线:
# config/routes.rb MyApp::Application.routes.draw do namespace :products do resources 'statistics', only: ['index'] do collection do get 'latest' end end end end
并将您的StatisticsController
放在命名空间中:
# app/controllers/products/statistics_controller.rb class Products::StatisticsController < ApplicationController def index @statistics = Statistic.chronologic render json: @statistics end def latest @statistic = Statistic.latest render json: @statistic end end