Patrick Berkeley
Patrick Berkeley

Reputation: 2286

Create an associated model from JSON

I have a server response that looks like:

comments: [
  0: {
    body: "test3",
    created_at: "2013-06-27T22:27:47Z",
    user: {
        email: "[email protected]",
        id: 1,
        name: "Tester"
    }
  }
]

And ember models:

App.Comment = DS.Model.extend({
  user: DS.belongsTo('App.User'),
  body: DS.attr('string')
});

App.User = DS.Model.extend({
  name: DS.attr('string'),
  email: DS.attr('string'),
});

How do I create an ember user model from the server's response?

Upvotes: 1

Views: 101

Answers (1)

Patrick Berkeley
Patrick Berkeley

Reputation: 2286

The solution if you're using rails active model serializers is to embed :ids, include: true:

app/serializers/comment_serializer.rb

class CommentSerializer < ActiveModel::Serializer
  embed :ids, include: true
  attributes :created_at, :body
  has_one :user
end

Just like the readme for active_model_serializers says, this will produce:

{
   "users":[
      {
         "id":1,
         "name":"Tester",
         "email":"[email protected]",
      }
   ],
   "comments":[
      {
         "event":"commented",
         "created_at":"2013-06-27T22:27:47Z",
         "body":"test3",
         "user_id":1
      }
   ]
}

Upvotes: 1

Related Questions