Bogdan Zurac
Bogdan Zurac

Reputation: 6451

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
                                 });

Upvotes: 5

Views: 1969

Answers (1)

GJK
GJK

Reputation: 37389

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.

Upvotes: 14

Related Questions