2015-06-02 59 views
0

我在我的Rails应用程序的宁静设置两个API控制器:Rails的JSON REST API:从父获取子类通过调用API

  • 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控制器

APIController:

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 

的ProductsController:

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 

感谢您的任何见解。

回答

0

你在你的路线需要嵌套的资源:

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 
0

您可以通过商店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为您提供PARAMS路线的一部分,大概在:store_id。请确认rake routes