How do I set an Ember Data polymorphic model in QU

2019-05-30 15:27发布

问题:

Background

I'm using Ember Data's ActiveModelAdapter on my project and defining a few models like so:

App.GiftCard = DS.Model.extend(
  destination: DS.belongsTo('destination', polymorphic: true)

  isCampaign: (->
    @get('destination.constructor') == App.Campaign
  ).property()
)

App.Destination = DS.Model.extend()

App.Campaign = DS.Model.extend()

My gift card model has a polymorphic relationship as the destination, and one of the types will be a Campaign.

This is all working as expected in the application, but now I'm trying to write a unit test for the isCampaign behavior using QUnit. The part I can't figure out is how can I create a GiftCard record and assign a Campaign as the polymorphic destination?

I have tried a few different ways. The first was to create a campaign record and assign it to the destination property:

First attempt

campaign = @store.createRecord('campaign', id: 1)
@gift_card = @store.createRecord('gift_card',
  id: 1
  amount: 100.00
  destination: campaign
)

But that gives the error:

Assertion Failed: You can only add a 'destination' record to this relationship

The other thing I tried was just to create a destination record instead and specify the type:

Second attempt

campaign = @store.createRecord('destination', id: 1, type: 'campaign')

@gift_card = @store.createRecord('gift_card',
  id: 1
  amount: 100.00
  destination: campaign
)

But in that case, destination.constructor is App.Destination, which is not what I want.

Other info

For what it's worth, the JSON from my API that sets up the relationship looks like this:

{
  "gift_card":{
    "id":1,
    "amount":100.0,
    "destination":{
      "type":"campaign",
      "id":5
    },
    "created_at":"2013-12-10T01:17:30.373Z"
  }
}

回答1:

I was able to get this to work by changing createRecord to push and specifying the destination as the ID, and the destinationType as the model:

@store.createRecord('campaign', id: 1)

@gift_card = @store.push('gift_card',
  id: 1,
  amount: 100.00,
  destination: 1,
  destinationType: 'campaign'
)