【问题标题】:How to nest collection routes?如何嵌套收集路线?
【发布时间】:2013-08-17 03:45:18
【问题描述】:

我在 Rails 3 应用程序中使用以下路由配置。

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

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

end

StatisticController 有两个简单的方法:

# 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

如何定义指向以下 URL 的路由:/products/statistics/latest


可选:我尝试将工作定义放入 concern,但失败并显示错误消息:

undefined method 'concern' for #&lt;ActionDispatch::Routing::Mapper ...

【问题讨论】:

    标签: ruby-on-rails collections separation-of-concerns nested-resources nested-routes


    【解决方案1】:

    我认为你可以通过两种方式做到这一点。

    方法一:

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

    方法2,如果products中有很多路由,你应该使用它来更好地组织路由:

    # 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 放在命名空间中:

    # 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
    

    【讨论】:

    • 方法一配置正确的路由指向:statistics#indexstatistics#latest。方法 2 生成的路由错误地指向:products/statistics#indexproducts/statistics#latest。我还设置了命名空间。
    • 你好,方法2只是指向products/statistics#index,因为它有一个命名空间:)如果你坚持使用statistics#index,就使用方法1。
    • 我错过了将控制器移动到子目录products。但是,将控制器命名为Products 会阻碍我StatisticsController 用于其他类,例如Articlesarticles/statistics 等等...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多