Say I have have an instance of ModelA, which can ‘hasMany’ ModelB instances. Given the id for a ModelB record that already exists on the server, how do I associate model A with model B? (The API docs only show how to do this by simultaneously creating a new model B instance and database record.)
As an example, say I have an app that can be used schedule meetings with Person and Meeting objects. The server might return JSON like this for a meeting:
Meeting:
{
id: '10',
purpose: 'Code review',
time: <timestamp>,
attendees: [ 501, 532 ]
}
Person:
{ id: 501, name: 'Kermit', email: 'kermit@thefrog.com' }
The models might be defined like this:
Ext.define('Person', {
extend: 'Ext.data.Model',
fields: ['id', 'name', 'email'],
proxy: {
type: 'rest',
url : 'data/people',
reader: { type: 'json' }
}
});
Ext.define('Meeting', {
extend: 'Ext.data.Model',
fields: ['id', 'purpose', 'time'],
hasMany: { model: 'Person', name: 'attendees' }
proxy: {
type: 'rest',
url : 'data/meetings',
reader: { type: 'json' }
}
});
I understand that once a meeting is loaded. I can call meeting.attendees() to access each Person model. But, given new attendee ID (e.g., 599), how do I add another person to the meeting? Is the only option to load the Person instance for id 599 and then add the that instance to ‘attendees’, like this?
Meeting.load(10, {
success: function(meeting) {
Person.load(599, {
success: function(person) {
meeting.attendees().add(person);
meeting.save();
}
});
}
})
When meeting.save() runs, would the POST correctly include just the ID of the person, like this?
{
id: '10',
purpose: 'Code review',
time: <timestamp>,
attendees: [ 501, 532, 599 ] <-- '599' is new attendee
}
Thanks!
To be honest… associations are best used for reading. Editing associated models aren’t the best as there is no way to configure a writer or anything. For the UI, yes, add a new model to the store you get from attendees() but you need to also send that back to the server.