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:
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With