Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Model Serializers belongs_to

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?
like image 752
Jesper Avatar asked Oct 29 '12 16:10

Jesper


People also ask

What is Active model Serializers?

What is Active Model Serializers? Serializer gem allows us to format our JSON easily. It will enable us to select only the data we want and access our relationships with a single request. Active Model Serializers provides a way of creating custom JSON in an object-oriented manner.

What do Serializers do for us?

Serialization converts an object in memory into a stream of bytes that can be recreated when needed. Serializers in Ruby on Rails convert a given object into a JSON format. Serializers control the particular attributes rendered when an object or model is converted into a JSON format.


1 Answers

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

like image 197
pjam Avatar answered Oct 04 '22 11:10

pjam