ebryn / ember-model

A lightweight model library for Ember.js
MIT License
525 stars 161 forks source link

Adding dynamic segment to model's urls #417

Open gabriel-dehan opened 9 years ago

gabriel-dehan commented 9 years ago

Hello !

I was looking for a way of having a dynamic part in my model's url. Something like this :

import Ember from "ember";

MyModel = Ember.Model.extend({
  // Relations and stuff
  some_resource: Ember.belongsTo("some-resource", { primaryKey:  'id' }),
});

MyModel.url = "/some_resource/:id/other_resource" // post/:id/comment for instance
MyModel.adapter = Ember.RESTAdapter.create();

export default MyModel;

But that does not work from the get go obviously. I thought of overwriting the buildURL function in my own adapter but we only get the record (before it's fetched, with nothing but a primary key) and I can't manage to get its belongsTo. Is there a built in way to do this or should there be one ?

Thanks !

gabriel-dehan commented 9 years ago

My take on this issue is the following :

For instance if I have a user model with a post belongsTo relation, it will create a relationMap object on the post record :

  somePostRecord.get('relationMap') === {
    user: 2 // Where 2 is the id of the user
  }
// Imports and stuffs

MyPostModel = Model.extend({
   // attributes
});

MyPostModel.adapter = Adapter.create();
MyPostModel.url = "user/:user_id/post";

// export and stuff

My Adapter should request user/2/post and get the post.

The code can be found here :

You'll notice how it was necessary to define a modelName attribute for the application model. I don't like it much but haven't figured a way out of this definition.

With minor changes, this could actually be implemented directly in the default Ember.RESTAdapter and Ember.Model.

What do you guys think of it ?