gpt4 book ai didi

ruby-on-rails - 如何嵌套采集路线?

转载 作者:行者123 更新时间:2023-12-02 21:53:03 25 4
gpt4 key购买 nike

我在 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

这会生成 URL /products/statistics StatisticsController 成功处理了该问题.

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


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

undefined method 'concern' for #<ActionDispatch::Routing::Mapper ...

最佳答案

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

方法一:

  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

关于ruby-on-rails - 如何嵌套采集路线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18244453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com