Beginner: How to create and save records which has relationships?


#1

My question may be asked earlier. Assume i have two models

App.Student=DS.Model.extend({
   name:DS.attr('string'),
   projects:DS.hasMany('project')
});

 App.Project=DS.Model.extend({
  name:DS.attr('string'),
  student:DS.belongsTo('student')
 });

Create Record:

1.How to create student record?
2.How to create project record?
3.Assume i have another two models which has many-to-many relationships. How to create record for those two models ?

Save:

1. I experienced issue in saving records which has relationships like hasMany. Any working fix available?

Is there any tutorials/documentation explaining all these.

Thanks in advance.

#2

If there is an relationship from students to projects, you can do this code.

var student1 = this.store.createRecord('student', {
  name: "Peter"
});
student1.save();

var project1 = this.store.createRecord('project',{
  ...
});
project1.save().then(function(response){
   student1.get('projects').pushObject(response);
   student1.save();
});

#3

So you don’t have to wait for student1 to save?

student1.save().then(function() {
  var project 1 = this.store.createREcord('project', ...
  ...
});

Wasn’t sure if the promise would be handled correctly or not?


#4

Thanks. Can you provide any doc/tutorial that explaining all these concepts?


#5
 Sorry, student1 is not getting saved with the project. I am using FixtureAdapter. 

#6

The Ember-Data docs are sketchty at the moment:

The Ember-Data api docs: http://emberjs.com/api/data/ The most important ones for you I would say are store.find, store.save, and it also explains which methods rely on promises.

This document on the github page also shows some good use cases, and tips on configuring ember-data to work with different APIs: https://github.com/emberjs/data/blob/master/TRANSITION.md

Also, I would say that you need to put more effort into your questions on this website. We can only help you if you provide enough information. Clear code examples, errors messages, etc…

If your using the fixture adapter, the data isn’t persisted anywhere. Every time you refresh the page the data is effectively re-initialized with the static arrays so perhaps it is working, just not as you expect.