【发布时间】: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