2

Rails 3 アプリケーションで次のルート構成を使用します。

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

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

end

には、次のStatisticController2 つの簡単な方法があります。

# 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これにより、 によって正常に処理されるURL が生成されますStatisticsController

次の URL につながるルートを定義するにはどうすればよい/products/statistics/latestですか?


オプション: 作業定義を問題にしようとしましたが、次のエラー メッセージで失敗します。

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

4

1 に答える 1

5

2つの方法でできると思います。

方法 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
于 2013-08-15T02:23:03.200 に答える