Ember: Using RESTAdapter with a nested API endpoint to POST a new record

Problem statement:
1. You are using Ember Data and have two models, say Blog and Post where Post has defined a DS.belongsTo('Blog') relationship.
2. Your API endpoint is nested, i.e., the endpoint to create a post is taking a POST request to /blog/:blogId/posts.
3. You are using RESTAdapter

The correct solution is to create an adapter override at app/adapters/post.js with the appropriate method to provide the correct endpoint URL. See the sample below:

import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({  
    urlForCreateRecord(modelName, snapshot) {
        let blogID = snapshot.belongsTo('blog').id;
        return `/${this.namespace}/blogs/${blogID}/posts`;

Here we are using the snapshot object to get the parent model and its ID to construct the URL. This is about the minimal override I could find, compared to overriding the complete createRecord, for example. Hope it helps!

comments powered by Disqus