How to nest collection routes?

2019-05-25 03:39发布

问题:

I use the following routes configuration in a Rails 3 application.

# config/routes.rb
MyApp::Application.routes.draw do

  resources :products do
    get 'statistics', on: :collection, controller: "statistics", action: "index"
  end

end

The StatisticController has two simple methods:

# 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

This generates the URL /products/statistics which is successfully handled by the StatisticsController.

How can I define a route which leads to the following URL: /products/statistics/latest?


Optional: I tried to put the working definition into a concern but it fails with the error message:

undefined method 'concern' for #<ActionDispatch::Routing::Mapper ...

回答1:

I think you can do it by two ways.

method 1:

  resources :products do
    get 'statistics', on: :collection, controller: "statistics", action: "index"
    get 'statistics/latest', on: :collection, controller: "statistics", action: "latest"
  end

method 2, if you have many routes in products, you should use it for better organized routes:

# config/routes.rb
MyApp::Application.routes.draw do

  namespace :products do
    resources 'statistics', only: ['index'] do
      collection do
        get 'latest'
      end
    end
  end

end

and put your StatisticsController in a namespace:

# 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