活动模型序列化程序belongs_to

这个问题与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 

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

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

 undefined method `belongs_to' for UserCombinationSerializer:Class 

我尝试将UserCombinationSerializer更改为:

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

在这种情况下,我没有错误,但subject是以错误的方式序列化 – 不使用SubjectSerializer

我的问题:

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

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

 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

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

 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 

在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