我在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
这会生成由/products/statistics
成功处理的网址StatisticsController
。
如何定义通往以下网址的路线:/products/statistics/latest
?
可选:我尝试将工作定义放入concern,但失败并显示错误消息:
undefined method 'concern' for #<ActionDispatch::Routing::Mapper ...
答案 0 :(得分:5)
我认为你可以通过两种方式来做到这一点。
方法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