Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I POST multiple models using Ember Data?

So let's say you have a User model which is set up to a fairly standard API. On the front end you have an Ember project which also has that User model. The normal creation call would be something like the following:

store.createRecord('user', {email: '[email protected]'}).save();

This would send off a POST request to something like /api/users. However, something fairly extensive API's support is the creation of multiple models at once. So for instance, instead of the POST call just sending a single object under user: {email: '[email protected]'} it would send an array of objects like users: [{email: '[email protected]'}, {email: '[email protected]'}, ...].

How I have seen this handled in ember is to just do multiple creation calls at runtime. However, this is terribly inefficient and I am wondering if Ember supports saving multiple models at the same time? How would you achieve this in Ember?

like image 453
Shawn Deprey Avatar asked Nov 09 '15 18:11

Shawn Deprey


People also ask

Is Ember a backend?

The most important thing to know is that Ember. js is completely backend-agnostic. You could write this part just as well in Ruby, PHP, Python or any other server language. In this lesson though we'll use Node.

What are ember models?

In Ember Data, models are objects that represent the underlying data that your application presents to the user. Note that Ember Data models are a different concept than the model method on Routes, although they share the same name.


1 Answers

You cannot save an array of models in a single POST request Ember Data as you describe it, however there is a way.

You can save a parent model which hasMany 'user' with the EmbeddedRecordsMixin, which will include either relationship ids or full records. Your serializer would look like -

import DS from 'ember-data';

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    users: { embedded: 'always' },
  }
});

Depending on your use case it may make sense to create a parent model only for this purpose which hasMany 'user'. If you want to use an existing model and don't always want to embed its user records there is an answer here.

If you do decide to save the models individually, you would want to do users.invoke('save'), which will trigger a POST for each model.

like image 190
andorov Avatar answered Oct 10 '22 11:10

andorov