Rails在资源中嵌套范围块

时间:2013-10-24 02:52:30

标签: ruby-on-rails ruby-on-rails-4 rails-routing

我正在尝试创建类似product/:id/monthly/revenue/product/:id/monthly/items_sold以及等效命名路由product_monthly_revenueproduct_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

但这给了我路线:

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

但这不是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

会给我路线

   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 :忘记提前包含此信息,但我在Rails 4.0.0上,使用Ruby 2.0.0-p247

2 个答案:

答案 0 :(得分:7)

真正的解决方案是使用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

答案 1 :(得分: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')