Ruby on rails 如何嵌套收集路线?
我在Rails3应用程序中使用以下路由配置Ruby on rails 如何嵌套收集路线?,ruby-on-rails,collections,separation-of-concerns,nested-resources,nested-routes,Ruby On Rails,Collections,Separation Of Concerns,Nested Resources,Nested Routes,我在Rails3应用程序中使用以下路由配置 # config/routes.rb MyApp::Application.routes.draw do resources :products do get 'statistics', on: :collection, controller: "statistics", action: "index" end end StatisticController有两种简单的方法: # app/controllers/statistic
# 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
#app/controllers/statistics_controller.rb
类统计控制器<应用程序控制器
def索引
@统计
呈现json:@statistics
结束
def最新版本
@统计
呈现json:@statistic
结束
结束
这将生成URL/products/statistics
,该URL由统计控制器
成功处理
如何定义指向以下URL的路由:/products/statistics/latest
可选:我尝试将工作定义放入,但失败并显示错误消息:
对#未定义的方法“关注”我认为可以通过两种方法来实现
方法1:
resources :products do
get 'statistics', on: :collection, controller: "statistics", action: "index"
get 'statistics/latest', on: :collection, controller: "statistics", action: "latest"
end
方法2,如果您在产品中有许多路线
,您应该使用它来更好地组织路线:
# 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
#app/controllers/products/statistics_controller.rb
类别产品::统计控制器<应用控制器
def索引
@统计
呈现json:@statistics
结束
def最新版本
@统计
呈现json:@statistic
结束
结束
方法1配置正确的路由指向:统计#索引
和统计#最新
。方法2生成的路由错误地指向:products/statistics#index
和products/statistics#latest
。我还设置了名称空间。您好,方法2只是指向products/statistics#index,因为它有一个名称空间:)如果您坚持使用statistics#index,就使用方法1。我没有将控制器移动到子目录products
。但是,将控制器命名为产品
会妨碍我将统计控制器
重新用于其他类别,如文章
和文章/统计
等。。。