How to nest collection routes?

妖精的绣舞 提交于 2019-12-22 18:24:08

问题


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


来源:https://stackoverflow.com/questions/18244453/how-to-nest-collection-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!