28

这个问题与 AMS 0.8 相关

我有两个模型:

class Subject < ActiveRecord::Base
  has_many :user_combinations
  has_ancestry
end

class UserCombination < ActiveRecord::Base
  belongs_to :stage
  belongs_to :subject
  belongs_to :user
end

和两个序列化器:

class UserCombinationSerializer < ActiveModel::Serializer
      attributes :id
      belongs_to :stage
      belongs_to :subject
end

class SubjectSerializer < ActiveModel::Serializer
  attributes :id, :name, :description, :subjects

  def include_subjects?
    object.is_root?
  end

  def subjects
    object.subtree
  end
end

当 aUserCombination被序列化时,我想嵌入整个主题子树。

当我尝试使用此设置时,我收到此错误:

undefined method `belongs_to' for UserCombinationSerializer:Class

我尝试将其更改UserCombinationSerializer为:

class UserCombinationSerializer < ActiveModel::Serializer
  attributes :id, :subject, :stage
end

在这种情况下,我没有收到任何错误,但是以subject错误的方式序列化了 - 不使用SubjectSerializer.

我的问题:

  1. 我不应该能够在序列化程序中使用belongs_to 关系吗?
  2. 如果没有 - 我怎样才能获得想要的行为 - 使用 SubjectSerializer 嵌入主题树?
4

3 回答 3

42

这不是很优雅,但它似乎正在工作:

class UserCombinationSerializer < ActiveModel::Serializer
  attributes :id, :stage_id, :subject_id

  has_one :subject
end

我真的不喜欢调用 has_one 而它实际上是一个 belongs_to 关联:/

编辑:忽略我对 has_one/belongs_to 歧义的评论,文档实际上很清楚:http ://www.rubydoc.info/github/rails-api/active_model_serializers/frames

于 2012-10-29T20:09:41.183 回答
6

在 Active Model Serializer 0-10-stable 中,belongs_to现在可用。

belongs_to :author, serializer: AuthorPreviewSerializer
belongs_to :author, key: :writer
belongs_to :post
belongs_to :blog
def blog
  Blog.new(id: 999, name: 'Custom blog')
end

https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/serializers.md#belongs_to

所以你可以这样做:

class UserCombinationSerializer < ActiveModel::Serializer
  attributes :id
  belongs_to :stage, serializer: StageSerializer
  belongs_to :subject, serializer: SubjectSerializer
end
于 2017-11-12T20:08:54.373 回答
4

如果你尝试这样的事情怎么办:

class UserCombinationSerializer < ActiveModel::Serializer
  attributes :subject,
             :stage,
             :id

  def subject
    SubjectSerializer.new(object.subject, { root: false } )
  end

  def stage
    StageSerializer.new(object.stage, { root: false } )
  end
end
于 2016-01-11T22:08:18.997 回答