5

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

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Liked the 2nd method as it has global effect. But good to know both versions exist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.