2

레일 3 애플리케이션에서 다음 라우트 구성을 사용합니다.수집 경로를 중첩하는 방법은 무엇입니까?

# 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 

이 성공적으로 StatisticsController에 의해 처리되는 URL /products/statistics를 생성하십시오 StatisticController

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

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

end 

는 두 가지 간단한 방법이 있습니다.

다음 URL로 연결되는 경로를 정의하려면 어떻게해야합니까? /products/statistics/latest?


옵션 : 나는 concern로 작업 정의를 넣어 시도했지만 오류 메시지와 함께 실패합니다

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

답변

5

난 당신이 두 가지 방법으로 그것을 할 수 있다고 생각합니다.

방법 1 :

# 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을 넣어 : 당신이 products 많은 경로가있는 경우

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

방법이, 당신은 더 나은 조직 노선을 위해 사용한다

# 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 
+0

방법 1은 올바른 경로 **를 구성합니다 :'statistics # index'와's tatistics # latest'. 방법 2는'products/statistics # index'와'products/statistics # latest'를 가리키는 경로 **를 잘못 생성합니다 **. 네임 스페이스도 설정했습니다. – JJD

+1

안녕하세요, 방법 2는 제품/통계 # index를 가리키고 있습니다. 네임 스페이스가 있기 때문에 :) # statistics # 통계를 계속 사용하려면 방법 1을 사용하십시오. – Bigxiang

+0

컨트롤러를 하위 디렉토리 'products'로 옮기지 않았습니다. 그러나, 컨트롤러를'Products'에 네임 스페이스 화하면'Articles'와'articles/statistics'와 같은 다른 클래스를 위해'StatisticsController' **를 다시 사용하는 것을 방해합니다 ... – JJD