【问题标题】:JSONApi not working for polymorphic relationships. RailsJSONApi 不适用于多态关系。导轨
【发布时间】:2017-10-16 22:19:48
【问题描述】:

我正在使用这个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 对吧?

【问题讨论】:

  • 您的可生产模型中有product_id 吗?
  • 所以错误是我使用的路线。我认为使用jsonapi_resource :products 而不是jsonapi_resources :products 会因为某种原因导致失败。
  • 我的products 表中有一个producible_id

标签: ruby-on-rails json-api


【解决方案1】:

正如错误所说,您的可生产模型中没有product_id。所以你们belongs_to :producible, polymorphic: true的关系不行了。

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

如果您对此有任何疑问,我建议您阅读有关 active record relations 的官方 Rails 文档。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    相关资源
    最近更新 更多