有条件地覆盖活动模型序列化器关联方法
Conditionally overriding an active model serializer association method
我正在编写一个包含 has_one :source
的序列化程序。 source
可以是多种不同的类型。当 source
是 overriding the association methods 的 Foo
时,我试图让 JSON 变小。我试过这个:
def source
return super unless source_type == 'Foo'
render json: source, serializer: LimitedFooSerializer
end
但后来我得到 没有超类方法`source'。
然后我尝试了:
def source
render json: source unless source_type == 'Foo'
render json: source, serializer: LimitedFooSerializer
end
但是那个错误 堆栈级别太深 ;大概是无限递归吧。
如何有条件地覆盖关联方法?
直接调用序列化程序有效:
def source
if source_type == 'Foo'
FooSerializer::LimitedFooSerializer.new(object.source)
else
object.source
end
end
我不得不使用 object.source
而不是 source
来避免递归。
我正在编写一个包含 has_one :source
的序列化程序。 source
可以是多种不同的类型。当 source
是 overriding the association methods 的 Foo
时,我试图让 JSON 变小。我试过这个:
def source
return super unless source_type == 'Foo'
render json: source, serializer: LimitedFooSerializer
end
但后来我得到 没有超类方法`source'。
然后我尝试了:
def source
render json: source unless source_type == 'Foo'
render json: source, serializer: LimitedFooSerializer
end
但是那个错误 堆栈级别太深 ;大概是无限递归吧。
如何有条件地覆盖关联方法?
直接调用序列化程序有效:
def source
if source_type == 'Foo'
FooSerializer::LimitedFooSerializer.new(object.source)
else
object.source
end
end
我不得不使用 object.source
而不是 source
来避免递归。