Search code examples
ember.jsember-dataember-router

EmberJS "detail" page fetches the model automatically - is this normal?


Long time reader - first time questioner here.

I am developing a medium sized application in EmberJS which is a framework that I have been using for a while.

Today I have realised that it fetches model data from the server without me writing any code.

I have a main route called "students". Then there is a "list" sub route where the model() function of this route calls the store to fetch all the students and lists them on a table.

On each row of this table I link to another sub route called "detail" where it accepts the ID of each student as an argument. However inside the route.js file for this route there is no model() function querying any information about the specific student from the server.

Ember does this automatically somehow as I can see the appropriate network request being made using chrome dev tools.

How is this happening and is it normal?

Thank you in advance.


Solution

  • The Ember router will automatically load a model if it detects a dynamic segment that ends in _id.

    Ember follows the convention of :model-name_id for two reasons. The first reason is that Routes know how to fetch the right model by default, if you follow the convention

    You mentioned that your api route is /api/student/details/:student_id and I would expect that your ember route is fairly similar.

    It detected _id, and called store.find('student', params.student_id) automatically for you when you navigated to that route.

    This is completely normal, and is one of the ways Ember encourages you to follow convention - If you do, you don't have to create as much boilerplate.

    If you want to avoid the second request, possibly because the list route pulls all relevant data, you can pass the student model instead of the student id.