Rails JSON 休息 API:通过 API 调用从父级获取子级 Class

Rails JSON Rest API: Getting Child Class from Parent via API Call

我的 Rails 应用程序中有两个 API 控制器用于 RESTful 设置:

如何编写 API 以便

http://localhost:3000/api/v1/stores/37/products

returns 只有那家商店的产品(在本例中是商店 #37)?我想我缺少实现这一目标的路由和控制器方法。

路线

    namespace :api, defaults: {format: 'json'} do
      namespace :v1 do
        resources :stores
        resources :licenses
      end
    end

API 控制器

API控制器:

    module Api
      module V1
        class ApiController < ApplicationController
          respond_to :json
          before_filter :restrict_access

          private

          def restrict_access
            api_app = ApiApp.find_by_access_token(params[:access_token])
            head :unauthorized unless api_app
          end
        end
      end
    end

商店控制器:

  module Api
    module V1
      class StoresController < ApiController

        def index
          respond_with Store.all
        end

        def show
          respond_with Store.find_by_id(params[:id])
        end
      end
    end
  end

产品控制器:

    module Api
      module V1
        class ProductsController < ApiController
          def index
            respond_with Product.all
          end

          def show
            respond_with Product.find_by_id(params[:id])
          end
        end
      end
    end

感谢您的任何见解。

您可以按商店 ID 确定产品范围。

class ProductsController < ApiController
  def index
    store = Store.find(params[:store_id])
    respond_with store.products
  end
end

如果你看看你的路线:

http://localhost:3000/api/v1/stores/37/products

您会发现 37 是您在参数中提供的路线的一部分,可能在 :store_id 中。检查 rake routes 以确保。

您想在路由中嵌套资源:

resources :stores do
  resources :products
end

所以你有那些路线:

GET        /stores/:id
GET/POST   /stores/:store_id/products
PUT/DELETE /stores/:store_id/products/:id

您可能还需要浅路由,以避免深度嵌套的资源:

resources :stores, shallow:true do
  resources :products
end

所以你有那些路线:

GET        /stores/:id
GET/POST   /stores/:store_id/products
PUT/DELETE /products/:id

获得路线后,您可以先加载父商店,然后使用产品关联:

@store = Store.find(params[:store_id])
@products = store.products