Ruby on Rails - 嵌套路由集合

时间:2017-11-04 05:54:57

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

我想以下列格式设置GET端点:

  

API / V1 /用户/类型/ {TYPE_ID}

示例:> api/v1/users/types/10

我目前的路由如下:

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :users do
        collection do 
          # other routes in the same namespace
          get "sync"
          post "register"

          # my attempt at making another collection for `types`
          collection do
            get "types"
          end

        end
      end
    end
  end
end

这是不正确的,它会引发错误:ArgumentError: can't use collection outside resource(s) scope。我的要求的路线格式是否正确?

2 个答案:

答案 0 :(得分:2)

试试这个

Rails.application.routes.draw do                                                                                                                 
  namespace :api do                                   
    namespace :v1 do                                  
      resource :users do                              
        resources :types, only: :show, param: :type_id
        collection do                             
          # other routes in the same namespace        
          get "sync"                                  
          post "register"                             
        end                                           
      end                                             
    end                                               
  end                                                 
end                                                   

在这里,我为用户使用资源而不是资源。并将类型转移到资源中。

答案 1 :(得分:2)

我相信答案是:

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :users do
        collection do
          get "sync"
          post "register"
          get "types/:type_id", action: 'types'
        end
      end
    end
  end
end

types是行动,您需要的是参数:type_id。 如果您运行rails routes,则会获得:

      Prefix Verb   URI Pattern                            Controller#Action
             GET    /api/v1/users/types/:type_id(.:format) api/v1/users#types

现在您可以转到http://localhost:3000/api/v1/users/types/10