Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define the ember data model for nested rest url

I am trying to do something that sounds simple but I can't find the solution.

My application needs to edit documents which contains pages.

Here is my model :

MyApplication.Document = DS.Model.extend({
    title: DS.attr('string'),
    pages: DS.hasMany('page', {async: true})
});
MyApplication.Page = DS.Model.extend({
    document: DS.belongsTo('document', {async: true}),
    title: DS.attr('string'),
    params: DS.attr(),
    objects: DS.attr()
});

And the routes :

MyApplication.Router.map(function () {
    this.resource('document', {path: '/document/:document_id'});
});
MyApplication.Document = Ember.Route.extend({
    model: function (params) {
        return this.store.find('document', params.document_id);
    }
});

When I load the document 1, the application call http://www.myserver.com/api/document/1.

The problem is that when I want to find a page of the document, it calls

  • http://www.myserver.com/api/pages/ID

instead of

  • http://www.myserver.com/api/document/1/pages/ID

Theses nested URL are important in my application.

I found different things on the subject like adding links in the JSON response :

{
    "document": {
        "id": "1",
        "title": "Titre du document",
        "pages": ["1", "2", "3"],
        "links": {"pages" : "pages"}
},

But when I call for the pages, it requests http://www.myserver.com/api/document/1/pages without the id.

I also try specify the document when I ask for the page :

this.store.find("page", 1, {document:1});

Can't find a complete documentation on this subject, so if someone can explain me what's wrong, I'll be happy.

Thank.

like image 734
thomaf Avatar asked Feb 10 '15 14:02

thomaf


2 Answers

Depends : EMBER DATA >= V1.0.0-BETA.9

The way to handle nested routes is hidden under release notes

  1. Need to send back the links with response like this

    {
        "document": {
        "id": 1,
        "title": "Titre du document",
        "links": {"pages" : "/documents/1/pages"}
    }
    
  2. You'll need to customize the adapter:page's buldUrl method like

    MyApplication.PageAdapter = DS.RestAdapter.extend({
      // NOTE: this is just a simple example, but you might actually need more customization when necessary
      buildURL: function(type, id, snapshot) {
        return '/documents/' + snapshot.record.get('document.id') + '/pages/' + id;
      }
    });
    
like image 116
code-jaff Avatar answered Sep 26 '22 14:09

code-jaff


@code-jaff answer adapted to Ember 2.1.0:

// app/adapters/page.js
import DS from './application'; // I suppose you have your adapter/application.js

export default DS.RESTAdapter.extend({
  buildURL: function(type, id, snapshot) {
    return this.host + '/' + this.namespace + '/documents/' + snapshot.record.get('document.id') + '/pages/' + id;
  }
});
like image 39
fguillen Avatar answered Sep 25 '22 14:09

fguillen