Search code examples
ember.jsember-data

Ember data lazy loading vs embedded?


I have the following models in my educational ember app.

App.Exam=DS.Model.extend({
    name: DS.attr('string'),
    subjects: DS.hasMany('subject')
});

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

App.SubjectCourse=DS.Model.extend({
    subject: DS.belongsTo('subject'),
    course: DS.belongsTo('course')
});

App.Course=DS.Model.extend({
    name: DS.attr('string'),

});

Each exam has many subjects.
Each subject belongs to an exam.
There is another table SubjectCourse which has information about which course belongs to which subject. Since one course can belong to multiple subject, I have used this table.

Now when I am requesting the data from the API, how should I load the related data?

In my app I want the user to be able to select the exam and see all the courses belonging to that exam and then search/filter by subject.

I could also approach this problem by using embedded json data. But is that the ember way of doing it ? Or is lazy loading the related data better in this scenario ?


Solution

  • How to side load data:

    If you want your subjects to be side loaded you need to add the following option:

    App.Exam=DS.Model.extend({
        name: DS.attr('string'),
        subjects: DS.hasMany('subject', {async: true})
    });
    

    Now, ember expects your API to send a JSON similar to this:

    {"name" => "examName", "subjects" => [1, 2, 3] } where 1, 2, 3 is representing the object ids of three subjects. Your exam record would now live inside your ember store and once you try to access its subjects the store would send a GET request for the specific subjects using their ids and update the exam record accordingly.

    When to side load data:

    It makes sense to side load data when you are confident that the ember store will already know the object. For example if many Exams share a certain subset of subjects, with side loading you would have to send those subjects only once, whenever later in time an exam is loaded that has subject 2 the ember store will just get the subject with id 2 from its store instead of sending another request.

    When not to side load data:

    On the other hand if exams do not share any common subjects, with side loading you would effectively send multiple requests every time you need an exam (one for the exam itself, and then one for every subject). This could generate a lot of requests and slows your application down. So when when you fetch a record and you know you will need its dependent records as well it makes more sense to embed them to save yourself network requests.