从JSON创建关联模型

时间:2013-06-27 22:55:21

标签: ember.js associations

我的服务器响应如下:

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

和ember模型:

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'),
});

如何根据服务器的响应创建一个ember用户模型?

1 个答案:

答案 0 :(得分:1)

如果您使用rails active model serializer,那么解决方案是embed :ids, include: true

应用程序/串行器/ comment_serializer.rb

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

就像the readme for active_model_serializers所说,这会产生:

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