Active Model Serializers belongs_to

Jesper picture Jesper · Oct 29, 2012 · Viewed 19.6k times · Source

This question pertains to AMS 0.8

I've got two models:

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

And two serializers:

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

When a UserCombination is serialized, I want to embed the whole subtree of subjects.

When I try to use this setup I get this error:

undefined method `belongs_to' for UserCombinationSerializer:Class

I tried changing the UserCombinationSerializer to this:

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

In this case I get no errors, but the subject is serialized in the wrong way - not using the SubjectSerializer.

My questions:

  1. Shouldn't I be able to use a belongs_to relation in the serializer?
  2. If not - how can I get the wanted behaviour - embedding the subject tree using the SubjectSerializer?

Answer

pjam picture pjam · Oct 29, 2012

This is not really elegant but it seems to be working :

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

  has_one :subject
end

I don't really like calling has_one whereas it's actually a belongs_to association :/

EDIT: Disregard my comment about has_one/belongs_to ambiguity, the doc is actually pretty clear about it: http://www.rubydoc.info/github/rails-api/active_model_serializers/frames