Rubix
Rubix

Reputation: 53

Ember.js : Modify request URL

I create an Ember app with a Symfony REST api. I also use the REST adapter for my requests.

I have 2 models in my app : users and their related comments. I already created CRUD operations for my user properties and now I focus on the CRUD operations for comments.

Model user.js

export default DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),

    comments: DS.hasMany('comment')
});

Model comment.js

export default DS.Model.extend({
    title: DS.attr('string'),
    message: DS.attr('string'),

    user: DS.belongsTo('user')
});

I have a route which shows all comments (and other data) of a given user. The request loads the user object and his relations. On the view I also have a form and an action to create a new comment for this user.

Route users/get.js

import Ember from 'ember';

export default Ember.Route.extend({

    id: null,

    model(params) {
        this.set('id', params.user_id);
        return this.get('store').findRecord('user', params.user_id, {include: 'comments'});
    },
});

Route users/get/comments.js

import Ember from 'ember';

export default Ember.Route.extend({
    model(params) {
        return this.modelFor('user.get', params.user_id);
    },
});

Controller users/get/comments.js

import Ember from 'ember';

export default Ember.Controller.extend({

    newComment: null,
    user: null,

    init: function() {
        this._super(...arguments);

        let comment = this.store.createRecord('comment');
        this.set('newComment', comment);
    },

    actions: {
        saveComment: function() {
            let user = this.get('model');
            let comment = this.get('newComment');

            comment.set('user', user);
            comment.save();
        }
    }
});

Everything works, except for the request sent to the backend. I loaded the comments from the user, so I expect a call to :

POST http://my-app.local/users/comments/

Instead the call is sent to :

POST http://my-app.local/comments/

Do you know why and how could I correct it ?

Second problem, the model is loaded from the 'user.get' route. This works because the user comes from this route to this page, but... It's doesn't work if the user enters directly the URL for comments. That sound logical, but I have no clue how to correct this problem... Can you help me ?

Upvotes: 1

Views: 772

Answers (1)

Kyle
Kyle

Reputation: 86

This can be done by rewrite the CommentAdapter.urlForCreateRecord method. Which affect new comment record requests.

adapters/comment.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
    urlForCreateRecord(modelName, snapshot) {
        return '/users/comments'; // the url you want
    }
});

There are several urlFor... method you might need to customise your url. Just check out the document http://devdocs.io/ember/classes/ds.buildurlmixin/methods#urlForCreateRecord

Upvotes: 2

Related Questions