活动模型序列化程序belongs_to

时间:2012-10-29 16:00:19

标签: ruby-on-rails active-model-serializers

此问题与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嵌入主题树?

3 个答案:

答案 0 :(得分:39)

这不是很优雅,但似乎有效:

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

答案 1 :(得分:3)

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

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

答案 2 :(得分:2)

在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