Ben*_*Lee 0 ruby-on-rails rails-routing ruby-on-rails-4
我想创建一个路径product/:id/monthly/revenue/,并product/:id/monthly/items_sold和等效命名路由product_monthly_revenue和product_monthly_items_sold,这些路由只会显示图表.我试过了
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
Run Code Online (Sandbox Code Playgroud)
但这给了我路线:
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
Run Code Online (Sandbox Code Playgroud)
其中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
Run Code Online (Sandbox Code Playgroud)
但这不是DRY,当我尝试添加更多像年度这样的类别时会变得很疯狂.当我想将所有图表合并到一个控制器中时,使用命名空间会强制我为每个命名空间创建一个新控制器.
所以我想总结的问题是:是否可以在没有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
Run Code Online (Sandbox Code Playgroud)
会给我路线
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
Run Code Online (Sandbox Code Playgroud)
与第一个块类似,是意外的,因为我希望如果范围嵌套在资源块中,则只有范围块中的路由会受范围影响,而不会影响资源块.
编辑2:忘记提前包含这些信息,但我在Rails 4.0.0上,使用Ruby 2.0.0-p247
小智 8
真正的解决方案是使用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
Run Code Online (Sandbox Code Playgroud)
参考:https://github.com/rails/rails/issues/12626
| 归档时间: |
|
| 查看次数: |
2343 次 |
| 最近记录: |