JSONApi不适用于多态关系。轨道

时间:2017-10-16 14:07:44

标签: ruby-on-rails json-api

我使用此gem并且我在实现多态关系时遇到了一些麻烦。

我有一个polymorphicproducts资源。我也有适当的控制器和路线。我也有常规的ActiveRecord模型:

我的模特:

class Product < ActiveRecord::Base
  include Priceable

  belongs_to :producible, polymorphic: true
...

我有这个问题,我在producible类中加入了BeerApples

module Producible
  extend ActiveSupport::Concern

  included do
    has_one :product, as: :producible, inverse_of: :producible

我的路线:

jsonapi_resource :products

/api/products/relationships/producible

我的资源(我听说我也需要多态资源)。

class Api::ProductResource < JSONAPI::Resource
  attributes :producible_type, :plan_id, :is_selling_enabled

  belongs_to :producible, polymorphic: true
end

class Api::ProducibleResource < JSONAPI::Resource
end

我的控制器:

module Api
  class ProductsController < Api::BaseJsonapiController
end
end

module Api
  class ProduciblesController < Api::BaseJsonapiController
  end
end

当我尝试导航到顶部列出的路线时,我收到此错误:

{
"errors": [
{
"title": "Missing Parameter",
"detail": "The required parameter, product_id, is missing.",
"code": "106",
"status": "400"
}
]
}

它很奇怪,因为这条路线似乎不需要product_id吗?

1 个答案:

答案 0 :(得分:0)

正如错误所述,您的可制作模型中没有product_id。因此,您的关系belongs_to :producible, polymorphic: true无效。

我认为您希望在产品型号中使用producible_id。在这种情况下,您必须将belongs_to关系切换为has_one关系,并将belongs_to放入可制作的模型中。

如果您有任何问题,我建议您阅读有关demo的官方rails文档。

我希望这会对你有所帮助

相关问题