如何在QUnit中设置一个Ember Data多态模型? [英] How do I set an Ember Data polymorphic model in QUnit?
问题描述
我使用Ember Data的 ActiveModelAdapter ,并定义了如下所示的几个模型:
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.
这在应用程序中的所有工作,但现在我试图写一个单元测试 isCampaign
使用QUnit的行为。我不能弄清楚的是,如何创建GiftCard记录并将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:
campaign = @store.createRecord('campaign', id: 1)
@gift_card = @store.createRecord('gift_card',
id: 1
amount: 100.00
destination: campaign
)
但是会出现错误: / p>
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:
campaign = @store.createRecord('destination', id: 1, type: 'campaign')
@gift_card = @store.createRecord('gift_card',
id: 1
amount: 100.00
destination: campaign
)
但在这种情况下, destination.constructor
是 App.Destination $ c $
But in that case, destination.constructor
is App.Destination
, which is not what I want.
其他信息
我的设置关系的API看起来像这样: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"
}
}
推荐答案
我可以通过将 createRecord
更改为 push
并指定目标为ID,并将destinationType作为模型:
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'
)
这篇关于如何在QUnit中设置一个Ember Data多态模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!