28

この質問は AMS 0.8 に関するものです

私は2つのモデルを持っています:

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

および 2 つのシリアライザー:

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 に答える