2013-10-24 70 views
0

我正在嘗試創建類似product/:id/monthly/revenue/product/:id/monthly/items_sold的路徑以及等效的命名路由product_monthly_revenueproduct_monthly_items_sold,並且這些路由只會顯示圖表。我試圖Rails資源中的嵌套範圍塊

resources :products do 
    scope 'monthly' do 
     match 'revenue', to: "charts#monthly_revenue", via: 'get' 
     match 'items_sold', to: "charts#monthly_items_sold", via: 'get' 
    end 
end 

但是這給了我的路線:

product_revenue GET /monthly/products/:product_id/revenue(.:format) charts#monthly_revenue 
product_items_sold GET /monthly/products/:product_id/items_sold(.:format) charts#monthly_items_sold 

其中monthly前將追加,而是和路線命名爲關閉。我知道我可能只是這樣做:

resources :products do 
    match 'monthly/revenue', to: "charts#monthly_revenue", via: 'get', as: :monthly_revenue 
    match 'monthly/items_sold', to: "charts#monthly_items_sold", via: 'get', as: :monthly_items_sold 
end 

但不幹燥,當我嘗試添加更多類別,如每年它變得瘋狂。當我想將所有圖表合併到單個控制器中時,使用命名空間會迫使我爲每個命名空間創建一個新的控制器。

所以我想總結的問題是:是否有可能命名空間路線沒有namspacing控制器?還是有可能整合創建命名路線的類別?

編輯:使用

resources :products do 
    scope "monthly", as: :monthly, path: "monthly" do 
    match 'revenue', to: "charts#monthly_revenue", via: 'get' 
    match 'items_sold', to: "charts#monthly_items_sold", via: 'get' 
    end 
end 

會給我的路線

monthly_product_revenue GET /monthly/products/:product_id/revenue(.:format) charts#monthly_revenue 
monthly_product_items_sold GET /monthly/products/:product_id/items_sold(.:format) charts#monthly_items_sold 

這類似於第一塊,是出乎意料的,因爲我想到,如果一個範圍嵌套在一個資源塊,只有範圍塊中的路由會受到範圍的影響,而不受資源塊的影響。

編輯2:忘了前面包含此信息,但我on Rails的4.0.0,使用Ruby 2.0.0-P247

回答

1

下面是我可能的做法:

periods = %w(monthly yearly) 
period_sections = %w(revenue items_sold) 

resources :products do 
    periods.each do |period| 
    period_sections.each do |section| 
     get "#{period}/#{section}", to: "charts##{period}_#{section}", as: "#{period}_#{section}" 
    end 
    end 
end 

也可以使用命名路由並通過params將值傳遞給控制器​​方法(請務必在使用前正確驗證):

resources :products do 
    get ":period/:section", to: "charts#generate_report", as: :report 
end 

# report_path(period: 'monthly', section: 'revenue') 
+0

謝謝,這是一個很好的方式,以編程方式創建的路由。我有時會忘記Rails仍然是Ruby,忘記了這樣的解決方案。 儘管'resources'塊中的'scope'影響資源塊仍然很奇怪。這是一個錯誤? –

+0

@ tempestfire2002做得很好,永遠不會忘記Rails是Ruby :)我不認爲'scope'是嵌套在'resource'塊中的。我沒有看到這方面的例子。請參閱此處參考:http:不過,我同意,我不會期望你收到的結果。 –

4

真正的解決方案是使用nested

resources :products do 
    nested do 
    scope 'monthly', as: :monthly do 
     get 'revenue', to: 'charts#monthly_revenue' 
     get 'items_sold', to: 'charts#monthly_items_sold' 
    end 
    end 
end 

編號:https://github.com/rails/rails/issues/12626

+0

這應該是被接受的答案 – ylecuyer