I’m writing a serializer that includes has_one :source
. source
can be a number of different types. I’m trying to make the JSON smaller when source
is a Foo
by overriding the association methods. I tried this:
def source
return super unless source_type == 'Foo'
render json: source, serializer: LimitedFooSerializer
end
But then I get no superclass method `source’.
Then I tried:
def source
render json: source unless source_type == 'Foo'
render json: source, serializer: LimitedFooSerializer
end
But that errors stack level too deep; presumably it’s an infinite recursion.
How can I conditionally override the association method?
Calling the serializer directly worked:
def source
if source_type == 'Foo'
FooSerializer::LimitedFooSerializer.new(object.source)
else
object.source
end
end
I had to use object.source
instead of source
to avoid the recursion.