Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Id is lost while trying to JSON.stringify Ember model

I'm trying to JSON.stringify() the model of a route inside the controller by using the below code. It works and it returns all model attributes, except for the actual id of the model. Can we receive the id as well?

    var plan = this.get('model');
    var reqBody = JSON.stringify(
                                 {
                                    plan,
                                    token
                                 });
like image 862
Bogdan Zurac Avatar asked Apr 08 '15 11:04

Bogdan Zurac


1 Answers

You need to pass in the includeId option to the toJSON method in order to get the ID in the JSON.

var plan = this.get('model');
var reqBody = JSON.stringify({
    plan: plan.toJSON({ includeId: true }),
    token
});

And if you didn't know, JSON.stringify() will call toJSON() for you (which is what is happening in your case). If you want to call JSON.stringify() instead of model.toJSON({}), you can always override it:

App.Plan = DS.Model.extend({
    toJSON: function() {
        return this._super({ includeId: true });
    }
});

That way JSON.stringify(plan) will give you exactly what you want.

like image 109
GJK Avatar answered Oct 26 '22 08:10

GJK