jsonapi-resources

JSONAPI Resource: has_one/many with polymorphic associations


I have a model Order that has addresses like this:

 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

An example of fields in the Address model is:

addressable_id: 1
addressable_type: "Order"

I defined an AddressResource, but I don't know what my OrderResource should look like. In this case:

# OrderResource
has_many :pick_up_addresses
has_one :destination_address

does not work.

If I add ?include=destination_address to the URL for Order, I get:

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

And for ?include=pick_up_addresses I get:

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

I've looked at the documentation for defining relations (http://jsonapi-resources.com/v0.9/guide/resources.html#Relationships), but I'm not sure any of these options defines what I need here.

PS - Attempting to add polymorphic: true still yields the following errors:

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

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

Solution

  • Figured it out. For anyone else needing help:

    In OrderResource:

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

    And in the Address model:

    def type
      'address'
    end