2

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 ...

JJD
  • 50,076
  • 60
  • 203
  • 339

1 Answers1

5

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
JJD
  • 50,076
  • 60
  • 203
  • 339
Bigxiang
  • 6,252
  • 3
  • 22
  • 20
  • Method 1 configures the **correct routes** pointing to: `statistics#index` and `statistics#latest`. Method 2 generates routes **incorrectly** pointing to: `products/statistics#index` and `products/statistics#latest`. I also set the namespace. – JJD Aug 15 '13 at 12:35
  • 1
    Hi, method 2 is just pointing to products/statistics#index, because it has a namespace :) If you persist to use statistics#index, just use method 1. – Bigxiang Aug 15 '13 at 13:28
  • I missed to move the controller into the subdirectory `products`. However, namespacing the controller to `Products` hinders me from **re-using the `StatisticsController`** for other classes such as `Articles` and `articles/statistics` and so on ... – JJD Aug 15 '13 at 15:40