JSONAPI 资源:has_one/many 具有多态关联

JSONAPI Resource: has_one/many with polymorphic associations

我有一个模型 Order,其地址如下:

 has_many :pick_up_addresses,
       -> { where(address_type: Address.address_types[:pick_up]) },
       as: :addressable, class_name: 'Address', dependent: :destroy


has_one :destination_address,
      -> { where(address_type: Address.address_types[:destination]) },
      as: :addressable, class_name: 'Address', dependent: :destroy

Address 模型中的一个字段示例是:

addressable_id: 1
addressable_type: "Order"

我定义了一个AddressResource,但我不知道我的OrderResource应该是什么样子。在这种情况下:

# OrderResource
has_many :pick_up_addresses
has_one :destination_address

无效。

如果我将 ?include=destination_address 添加到订单的 URL,我得到:

undefined method `destination_address_id' for class `#<Class:0x007fe321b8cae8>'

对于 ?include=pick_up_addresses 我得到:

undefined local variable or method `object' for #<Api::V2::AddressResource:0x007fe32abc90c0>\nDid you mean?  object_id

我查看了定义关系的文档 (http://jsonapi-resources.com/v0.9/guide/resources.html#Relationships),但我不确定这些选项是否定义了我在这里需要的内容。

PS - 尝试添加 polymorphic: true 仍然会产生以下错误:

undefined method `type' for #<Address:0x007fe32f08d1c0> # for pick_up_address

undefined method `destination_address_id' for class `#<Class:0x007fe322db5f58>'" # for destination_address

想通了。对于其他需要帮助的人:

OrderResource中:

has_many :pick_up_addresses, polymorphic: true
has_one :destination_address, polymorphic: true, foreign_key: 'addressable_id'

并且在 Address 模型中:

def type
  'address'
end