2

我在 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/statisticsStatisticsController.

如何定义通向以下 URL 的路由:/products/statistics/latest


可选:我尝试将工作定义置于关注点,但失败并显示错误消息:

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

4

1 回答 1

5

我认为你可以通过两种方式做到这一点。

方法一:

  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
于 2013-08-15T02:23:03.200 回答