Reputation: 5212
I'm new to using ember data and I'm not clear on exactly how the relationships actually link up to the correct records:
for example let's say I have a transaction and recipient model. The relationship is one to many transactions to recipient. So I as I understand I would have something similar to:
models/transaction.js
import DS from 'ember-data';
export default DS.Model.extend({
recipient: DS.belongsTo('recipient'),
date: DS.attr('date'),
amount: DS.attr('string')
}).reopenClass({
FIXTURES: [
{
id: '1',
date: '2014/10/06',
recipient: ??
}
]
});
models/recipient.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
transactions: DS.hasMany('transaction')
}).reopenClass({
FIXTURES: [
{
id: '1',
name: 'Kurt',
transactions: ??
}
]
});
So my question is how do you declare which transaction records belongs to which specific recipient record?
Thanks for any help.
Upvotes: 0
Views: 527
Reputation: 5212
Here's a sample jsbin showing a working implementation of ember data relational mapping in action:
http://jsbin.com/jihota/3/edit?html,js,output
One of the issues I was having was not understanding that in the template I needed to reference joined table data via 'syntax' so for example a transaction row of data that joins a recipient based on recipient id you would use something like {{recipient.name}}
instead of just {{name}}
in the handlebars file to output that joined column.
Upvotes: 0
Reputation: 439
I believe this has already been answered but I cannot find the question to reference it here but I had to fight with this for a while too.
Basically, if you declare one of the properties on your model with DS.hasMany()
the model will be expecting and array of ID's while if you use DS.belongsTo()
the model will expect you to provide just the associated ID.
EDIT: Ember-data is expecting your data to pretty much follow what is described here: http://jsonapi.org/
So in your example you should go like this:
// models/transaction.js
import DS from 'ember-data';
export default DS.Model.extend({
recipient: DS.belongsTo('recipient', {async:true}),
date: DS.attr('date'),
amount: DS.attr('string')
}).reopenClass({
FIXTURES: [
{
id: '1',
date: '2014/10/06',
recipient: 1
}
]
});
//models/recipient.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
transactions: DS.hasMany('transaction', {async:true})
}).reopenClass({
FIXTURES: [
{
id: '1',
name: 'Kurt',
transactions: [1]
}
]
});
Please note that I added the {async:true}
options hash to the relationship declarations, this will enable your routes to fetch the contents of the relationship asyncronously before presenting the model to the controller (see: http://emberjs.com/api/data/#method_hasMany).
Upvotes: 1