我正在嘗試創建類似product/:id/monthly/revenue/
和product/:id/monthly/items_sold
的路徑以及等效的命名路由product_monthly_revenue
和product_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
謝謝,這是一個很好的方式,以編程方式創建的路由。我有時會忘記Rails仍然是Ruby,忘記了這樣的解決方案。 儘管'resources'塊中的'scope'影響資源塊仍然很奇怪。這是一個錯誤? –
@ tempestfire2002做得很好,永遠不會忘記Rails是Ruby :)我不認爲'scope'是嵌套在'resource'塊中的。我沒有看到這方面的例子。請參閱此處參考:http:不過,我同意,我不會期望你收到的結果。 –