我有一个模型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
添加到订单的网址,我会得到:
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
答案 0 :(得分:1)
想出来。对于其他需要帮助的人:
在OrderResource
:
has_many :pick_up_addresses, polymorphic: true
has_one :destination_address, polymorphic: true, foreign_key: 'addressable_id'
在Address
模型中:
def type
'address'
end