mercredi 30 novembre 2016

Ember Data Relationships representations - create record not working

I have a User and a Message model that look like this:

//models/user.js

export default DS.Model.extend({
  name: DS.attr('string'),
});

//models/message.js

export default DS.Model.extend({
  body: DS.attr('string'),
  sender: DS.belongsTo('user', { inverse: null }),
  receiver: DS.belongsTo('user', { inverse: null }),
  user: DS.belongsTo('user')
});

Here's how the messages/message route looks like:

//messages/message/route.js

export default Ember.Route.extend({
model(params) {
  return Ember.RSVP.hash({
      messages: this.store.query('message', { filter: {user: params.user}   }),
      user: this.store.findRecord('user', params.user),
    });
  },

  setupController(controller, models) {
    controller.set('messages', models.messages);
    controller.set('user', models.user);
  }
});

and in the router.js I have

this.route('messages', function() {
  this.route('message', { path: ':user' });
});

So basically when you go to /messages/{user_id} you can view all the messages the current user has with the an user that has the {user_id}. Here's a JSON response I get from the server when visiting messages/5

{
"messages": [
  {
    "id": 10,
    "sender": 1,
    "receiver": 5,
    "body": "Hello world!",
    "user": 5
  },
  {
    "id": 7,
    "sender": 1,
    "receiver": 5,
    "body": "Sorry, I don't get it!",
    "user": 5
  },
  {
    "id": 6,
    "sender": 5,
    "receiver": 1,
    "body": "Is it possible?",
    "user": 5
  }
]

}

Now when trying to create a new message there's no sender, receiver or user ids to associate the new record created with, in order to send these over to the server.

Here's what I have in the payload

{
  "body":"New message",
  "sender":null,
  "receiver":null,
  "user":null
}

It's clear I'm doing something wrong with the relationships and not sure how to handle these.




Aucun commentaire:

Enregistrer un commentaire