Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a model manually with EmberData

I have an Ember app with a login form which returns the current user in JSON format after successful login.

Using createRecord sets the returned JSON attributes directly on the model. For instance, is_private becomes user.is_private, not user.get('isPrivate')?

How do I load the user model so that the attributes are set correctly and I don't have to re-fetch it using the id?

like image 400
bschaeffer Avatar asked Apr 09 '13 16:04

bschaeffer


1 Answers

As of a few days ago in ember data 1.0 beta you can use pushPayload to load data directly into the store. For example if you get data pushed to your app through WebSockets (we use the Heroku add-on Pusher). You can call it on the store (source) directly and it will pass it through the appropriate serializer:

var postsJSON = {
  posts: [
    {id: 1, post_title: "Great post"}
  ]
}

this.store.pushPayload('post',postsJSON)

NOTE that it will not currently load a singular object (ie post: {id: 1, post_title:"First!"}) - you need to format it as plural with an array.

DS.RESTSerializer has pushPayload as well (source), in which case you need to pass it the store instead.

I highly encourage reading the source code before using, as it looks like the implementation of it will be revisited.

like image 165
andorov Avatar answered Jan 30 '23 00:01

andorov