[英]How to create a object in ember-cli-mirage?
I have a foo
model that hasMany bar
and bar
belongsTo baz
.我有一个
foo
模型,它 hasMany bar
和bar
BeingsTo baz
。 How can I include the creation of baz
when a foo
is created together with it's bar
?当
foo
与其bar
一起创建时,如何包含baz
创建? Whenver a foo
is created a 10 bar
must create and a baz
is created for each bar
每当创建
foo
必须创建 10 个bar
并为每个bar
创建一个baz
On my /factories/foo.js
I have a在我的
/factories/foo.js
我有一个
afterCreate(foo, server) {
server.createList('bar', 10, { foo });
}
One option would be to have the bar
factory create its own baz
:一种选择是让
bar
工厂创建自己的baz
:
// factories/bar.js
export default Factory.extend({
afterCreate(bar, server) {
bar.update({
baz: server.create('baz')
})
}
})
This way, every time server.create('bar')
is called (no matter where), each bar would get updated with its own baz
.这样,每次调用
server.create('bar')
(无论在哪里),每个 bar 都会更新为自己的baz
。
You could even use the association helper to do this for you – it basically takes care of this special case of creating a belongsTo
relationship whenever the base model is created:你甚至可以使用关联助手来为你做这件事——它基本上会在创建基础模型时处理这种创建
belongsTo
关系的特殊情况:
import { Factory, association } from 'ember-cli-mirage';
// factories/bar.js
export default Factory.extend({
baz: association()
})
You could also do it directly from the foo
factory:您也可以直接从
foo
工厂执行此操作:
// factories/foo.js
afterCreate(foo, server) {
server.createList('bar', 10, { foo }).forEach(bar => {
bar.update({
baz: server.create('baz')
})
});
}
Just note that base factories should be the minimal valid descriptions of your models + their relationships – if you put these auto-creating relationships in each base factory and then someone wants to write a test for a situation where these relationships don't exist, it'll be difficult for them.请注意,基础工厂应该是您的模型及其关系的最小有效描述——如果您将这些自动创建的关系放在每个基础工厂中,然后有人想为这些关系不存在的情况编写测试,它对他们来说会很困难。 The traits feature is designed specifically to alleviate this sort of thing:
特征特性是专门为缓解这种情况而设计的:
// factories/bar.js
Factory.extend({
withBaz: trait({
baz: association()
})
})
// factories/foo.js
Factory.extend({
afterCreate(foo, server) {
server.createList('bar', 10, 'withBaz', { foo });
}
})
Also be sure to give the factory best practices guide a read!另外一定要阅读工厂最佳实践指南! :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.