【问题标题】:Rails JSON Rest API: Getting Child Class from Parent via API CallRails JSON Rest API:通过 API 调用从父类获取子类
【发布时间】:2015-06-02 04:19:14
【问题描述】:

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

  • StoresController(有很多产品)
  • ProductsController(有一个商店)

如何编写 API 以便

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

只返回该商店的产品(在本例中为商店#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

StoresController:

  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

感谢您的任何见解。

【问题讨论】:

    标签: ruby-on-rails json rest has-many belongs-to


    【解决方案1】:

    您希望在路由中嵌套资源:

    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
    

    【讨论】:

      【解决方案2】:

      您可以通过商店 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 以确保。

      【讨论】:

        猜你喜欢
        • 2021-11-10
        • 2017-07-09
        • 1970-01-01
        • 2015-11-30
        • 2015-11-17
        • 1970-01-01
        • 2020-11-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多