小编ben*_*ton的帖子

使用Rails + active_model_serializers在EmberJS中加载具有非标准类名的对象

我在Rails中有一些模型看起来像这样:

class Issue < ActiveRecord::Base
  belongs_to :reporter, class_name: 'User'
  belongs_to :assignee, class_name: 'User'
  has_many :comments
end

class User < ActiveRecord::Base
end

class Comment < ActiveRecord::Base
end
Run Code Online (Sandbox Code Playgroud)

像这样的序列化器:

class IssueSerializer < ActiveModel::Serializer
  attributes :id
  embed :ids, include: true

  has_one :reporter, :embed => :ids
  has_one :assignee, :embed => :ids
end

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name
end

class CommentSerializer < ActiveModel::Serializer
  attributes :id, :body
end
Run Code Online (Sandbox Code Playgroud)

这会生成类似于以下内容的JSON:

{
  "issues": [
    {
      "id": 6,
      "reporter_id": 1,
      "assignee_id": 2,
      "comment_ids": [
        3
      ]
    }, …
Run Code Online (Sandbox Code Playgroud)

ember.js ember-data active-model-serializers

7
推荐指数
1
解决办法
1576
查看次数