Grape api - 如何发布嵌套资源?
问题描述:
所以,我有这个系统我正在使用rails 4和葡萄Api。基本上它汇总了关于在车辆上执行的维护服务的信息。我的模型是这样定义的:Grape api - 如何发布嵌套资源?
# service.rb
class Service < ActiveRecord::Base
has_many :service_items
#service_item.rb
class ServiceItem < ActiveRecord::Base
belongs_to :service
我在实现一个API,因此外部应用程序可以在我的系统上发布服务。每个服务都有一个或多个关联服务项目的列表。我有一个路由,如:example.com/api/v1/services for POST。我的问题是,如何让它接受一个包含服务属性和service_items属性嵌套的帖子?
我读葡萄文档,开始是这样的:
#service_providers_api.rb
resource :services do
desc "Post a Service"
params do
#requires :category_id, type: Integer
requires :description, type: String
requires :plate, type: String
requires :mileage, type: Integer
requires :date, type: Date
optional :cost, type: BigDecimal
requires :service_items do
requires :description, type: Integer
end
end
post do
.
.
.
end
end
但是我不知道我怎么能安装后的数据为这个工作。 是否可以像这样在单个请求中完成所有这些操作,还是必须将每个请求分开?例如一个POST接收服务,然后为每个关联的service_item提供一系列POST。在这种情况下推荐的最佳方法是什么?
答
params do
requires :service_items, type: Hash do
requires :description, type: Integer
end
end
需要两个参数,您必须提供一个类型。在你的情况下,哈希